Dynamic dropdown option load dissapears html modal dialog - google-sheets

My Html form has dropdown which load dynamic options using api request. I'm using google HTML Service to link google app script with html file. My problem is my modal dialog getting disappear as soon as it appears.
======== Script ========
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Call API')
.addItem('Display results','html')
.addToUi();
}
function html(){
var html = HtmlService.createTemplateFromFile('load');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Input API Creddentials');
}
function getClients() {
var response = UrlFetchApp.fetch("http://myurl does here");
var fact = JSON.parse(response.getContentText());
var optionsHTML = [];
for (var i = 0; i < fact.length-1;i+=1) {
optionsHTML.push(fact[i].clientId.client);
}
SpreadsheetApp.getUi().alert(optionsHTML);
return optionsHTML;
}
======= HTML File ====
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form >
<div>
<select id="optionList" name="optionList">
<option>Loading...</option>
</select>
</div>
Username:
<input type="text" name="username"> <br />
Password:
<input type="password" name="password"> <br />
<input type="button" value="OK" onclick="google.script.run.callNumbers(this.parentNode);google.script.host.editor.focus();" />
</form>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function () {
google.script.run.withSuccessHandler(buildOptionList)
.getClients();
});
function buildOptionList(clients) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < clients.length; i++) {
list.append(new Option(clients[i]));
}
}
</script>
</html>

The problem occurs due to
// The code in this function runs when the page is loaded.
$(function () {
google.script.run.withSuccessHandler(buildOptionList)
.getClients();
});
because getClients() shows an alert and Google Apps Script doesn't allow to have a Google Sheets UI alert and modal dialog shown simultaneosly.

Related

How to add googlesheet checkbox to the google sheet toolbar

I am a starter in coding in Googlesheets (google scripts). I want to create a google script to add a checkbox to the toolbar of the google sheet. Can anybody help me on this?
You cannot add a checkbox into the toolbar but you can create an HTML custom sidebar with checkboxes
For this, use Google Apps Script
Follow the guide for custom sidebar creation
Create an html file with checkboxes
Use google.script.run to communicate between serverside and client side of the code
Sample:
Code,gs
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Custom Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setTitle('My custom sidebar')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function setValue(checked) {
var value;
if(checked == true){
value = "number 1";
} else{
value = "number 2";
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getActiveSheet().getActiveCell();
cell.setValue("You clicked the checkbox: " + value);
};
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<input id="check" type="checkbox" >Click me <br>
<input type="checkbox" > Or me <br>
<input type="button" value="set value" onclick="evaluateInput()">
</div>
<script>
function evaluateInput() {
var checkedFirst = document.getElementById("check").checked;
google.script.run
.withFailureHandler(onFailure)
.setValue(checkedFirst);
};
function onFailure(error) {
console.log(error.message);
};
</script>
</body>
</html>

Running youtube data api from file:///

I am creating a webworks application, so my code is not being placed on a server. The youtube data api does not work when accessing from your local file system, but that it how my application works. I need a work around, or a way to make a local private web server with pure js, no command line tools.
html
<!DOCTYPE HTML>
<html>
<head>
<title>add song</title>
<link type="text/css" href="../css/AS_Style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<p id="response">a</p>
<form action="#">
<p><input type="text" id="search" placeholder="Type something..." autocomplete="off" class="form-control" /></p>
<p><input type="submit" value="Search" class="form-control btn btn-primary w100"></p>
</form>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="../js/AS.js"></script>
<script src="https://apis.google.com/js/api.js"></script>
<script>
function init() {
gapi.client.init({
'apiKey':'key here',
});
search();
}
gapi.load('client',init);
</script>
</body>
</html>
JavaScript
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
function search() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
};
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
Can you show the code you're using to call Youtube's API? You can get the API data with pure javascript:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=CHANNEL_ID&maxResults=1&fields=items&order=date&key=API_KEY", false);
xhr.send();
document.write(xhr.responseText);
Did you try triggering a shell script via javascript, and making the shell script run the API code?
Apparently this worked: https://stackoverflow.com/a/21484756/7922428
Youtube API doesnt work without connection to the internet, which when your locally testing, is done through local servers.
Here are my suggestions:
Use Nodejs
Use python -m SimpleHTTPServer

Is onchnge() function works in jquerymobile 1.4.2

I am using jquerymobile 1.4.2.This the code which i am using in my page
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"> </script>
</head>
<body>
<script>
function myFunction()
{
document.getElementById("myText").disabled=true;
}
</script>
<p>Click the button to disable the text field.</p>
<select onchange="myFunction()"><option>1</option><option>2</option></select>
First Name: <input type="text" id="myText">
</body>
</html>
The above program works fine But if i change that to this code
<script>
function myFunction()
{
document.getElementById("myText").disabled=false;
}
</script>
<p>Click the button to disable the text field.</p>
<select onchange="myFunction()"><option>1</option><option>2</option></select>
First Name: <input type="text" id="myText" disabled="disabled">
Then its not working please help me how to make text field enable using onchange() function
jQM enhances the input and creates a Textinput widget which has its own enable/disable methods (http://api.jquerymobile.com/textinput/#method-disable)
In your example, to enable the input:
function myFunction() {
$("#myText").textinput("enable");
}
Also, you should use unobtrusive javascript and the jQM page functions. e.g. remove the onclick from the markup:
<select id="theSelect" >
<option>1</option>
<option>2</option>
</select>First Name:
<input type="text" id="myText" disabled="disabled" />
Add the handler in the pagecreate jQM event:
function myFunction(selVal) {
if (selVal == '2'){
$("#myText").textinput("enable");
} else {
$("#myText").textinput("disable");
}
}
$(document).on("pagecreate", "#page1", function () {
$("#theSelect").on("change", function(){
var v = $(this).val();
myFunction(v);
});
});
Here is a DEMO

Browser History entry when POST form to to iframe with javascript (IE)

Basically i want to automatically POST content to a form without using XMLHttpRequest.
The site works fine but there is a problem with the browser history when getting back to the page by clicking the browser back button.
My site looks like this:
<!DOCTYPE html>
<html>
<head runat="server">
<title>History Problem</title>
<script>
window.onload = function () {
try {
if ("<%= Request.Form["hiddenField1"] == null %>" == "True") {
var theForm = document.getElementById("myForm");
var theIframe = document.createElement('iframe');
theIframe.id = theIframe.name = "myIframe";
document.body.appendChild(theIframe);
theForm.hiddenField1.value = "SomeValue";
theForm.submit();
}
}
catch (e) {
var x = e;
}
};
window.onunload = function () { };
</script>
</head>
<body>
<form runat="server" id="myForm" action="" target="myIframe" method="post">
<input type="hidden" id="hiddenField1" name="hiddenField1" />
</form>
<br />
External Link
</body>
</html>
The trace shows that there is a GET and a POST request. everything is fine so far. But if you click on "External Link" (google.com) and then back to the site, you'll see two history entries for the test site. Also the google.com history entry seems to be gone.
This happens only in Internet Explorer.
Any ideas?

jquery unable to bind functions

I am trying to attach onBlur and onFocus handler to a SSN input field. However, I am seeing an error saying object has no method 'ON'. The code is at http://jsfiddle.net/H4Q5f/
As you can see, I commented out to figure out the details, however had no luck so far. Any help is appreciated. For convenience, here is the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" src="../../appjavascript/ssa/mkwr/mytest.js"></script>
</head>
<body>
<div data-role="page" id="MyTestPage">
<div data-role="header" data-position="fixed" data-logo="true" data-tap-toggle="false" data-fullscreen="false" >
<h1> Page Title </h1>
</div>
<div data-role="content">
<div class="content-primary divcontent">
<h1 class='h1title'>Using This App</h1>
<p> Here are the instructions </a>
</p>
</div>
<div class="inputdata">
<br /> <br />
<input type="text" name="accessCode" id="AccessCode" value="" placeholder="Access Code:" /> <br />
<input type="text" id="ssn1" class="ssn" value="" placeholder="SSN1:" /> <br />
<input type="text" id="ssn2" class="ssn" value="" placeholder="SSN2:" /> <br />
</div>
<input type="button" id="myalert" value="Next" />
</div>
<!-- /content -->
</body>
</html>
And here is the java script
if (typeof TEST == "undefined" || !TEST) {
var TEST = {};
}
( function() {
TEST.mkwr = {
init : function() { // this is a public function
$("[data-role='page']").on("pagebeforeshow", TEST.mkwr.hideError());
$("[data-role='page']").on("pageshow", TEST.mkwr.setHandlers());
},
// On Blur, we need to add the '-'s if they doesn't exist so the user
// view edit the entered value formatted
ssnOnBlurHandler : function(input) { // Auto format SSN on blur
if ($(input).val().length == 9) {
var _ssn = $(input).val();
var _ssnSegmentA = _ssn.substring(0, 3);
var _ssnSegmentB = _ssn.substring(3, 5);
var _ssnSegmentC = _ssn.substring(5, 9);
$(input).val(
_ssnSegmentA + "-" + _ssnSegmentB + "-" + _ssnSegmentC);
}
}, // _ssnOnBlurHandler
// On focus, we need to remove the '-'s if they exist so the user
// can edit the entered value
ssnOnFocusHandler : function(input) {
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
if ($(input).val().length == 11) {
var _ssn = $(input).val();
var _ssnSegmentA = _ssn.substring(0, 3);
var _ssnSegmentB = _ssn.substring(4, 6);
var _ssnSegmentC = _ssn.substring(7, 11);
$(input).val(_ssnSegmentA + _ssnSegmentB + _ssnSegmentC);
}
}, // _ssnOnFocusHandler
// Hide all errors
hideError : function() {
$(".error").hide(); // Hide all errors
},
setHandlers : function() {
alert("Set Handlers");
// $(".ssn").each( function() {
// var input = this; input.blur(TEST.mkwr.ssnOnBlurHandler(input))
// });
// $(".ssn").each( function() {
// var input = this; input.focus(TEST.mkwr.ssnOnFocusHandler(input))
// });
}
};
})(); // end the anonymous function
$("[data-role='page']").bind("pageinit", TEST.mkwr.init());
I found a couple of issues with the code on the jsfiddle. Here is an updated one that is working to fire handlers and parse code. It looks like your ssn logic might need to be fixed a little but everything is getting you to there.
http://jsfiddle.net/H4Q5f/10/
The problems I saw were partly what was mentioned before you were using .on instead of .bind given the jquery version. But also you were not setting your handlers but rather firing your handlers. You had this:
input.bind("blur",TEST.mkwr.ssnOnBlurHandler(input))
which would return the result of the function to the set method which is not what you were looking for. So I changed it to this:
input.bind("blur",TEST.mkwr.ssnOnBlurHandler)
So now you are passing the handler to the set method so that it will fire when the event takes place.
Hope this makes sense.
The .on() function was introduced in jQuery 1.7. The code you've posted above includes jQuery 1.6.4 (<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>), which doesn't have that function. You can either upgrade to the latest version of jQuery (recommended) or use the equivalent function - .bind() - for the older versions.

Resources