I'm not usually working with web, so not very familiar with JS/HTML tricks.
I'm trying to create a Google spreadsheet with a sidebar.
The sidebar has 2 combo boxes and a button, and I expect that when the button is clicked the relevant cell in the spreadsheet will be populated with data based on the combo box selection.
Here is what I have so far:
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function update(){
val qEl = document.getElementById("quarter");
val q = qEl.options[qEl.selectedIndex].value;
val lEl = document.getElementById("l2");
val l = qEl.options[lEl.selectedIndex].value;
google.script.run.update(q, l);
}
</script>
Select
<select id="l2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
Select
<select id="quarter">
<option value="C6:N6">Q1</option>
<option value="O6:Z6">Q2</option>
<option value="AA6:AL6">Q3</option>
<option value="AM6:AX6">Q4</option>
</select>
</br>
<input type="button" value="Add" onclick="update()"/>
</body>
</html>
Then the Google script code:
function update() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var html = HtmlService.createHtmlOutputFromFile('AddLarge')
.setTitle('Add large item')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
function updateLarge(cell, value) {
SpreadsheetApp.getActive().getActiveSheet().getRange(cell).setValue(value);
}
This is not working.... :\
How about the following modifications?
Modification points :
In order to declare a variable, it uses var at GAS. I think that this might be a typo.
For var l = qEl.options[lEl.selectedIndex].value;, qEl is used. So a value selected at "quarter" is retrieved. I think that var l = document.getElementById("l2").value; can be also used.
In the case of google.script.run.update(q, l);, q, l is sent to update() of GAS script. In your case, I think that q, l should be sent to updateLarge(cell, value).
When these are reflected to your script, your script becomes below. Please do this modification to javascript in HTML. I think that your GAS script works fine.
From :
<script>
function update(){
val qEl = document.getElementById("quarter");
val q = qEl.options[qEl.selectedIndex].value;
val lEl = document.getElementById("l2");
val l = qEl.options[lEl.selectedIndex].value;
google.script.run.update(q, l);
}
</script>
To :
<script>
function update() {
var qEl = document.getElementById("quarter");
var q = qEl.options[qEl.selectedIndex].value;
var lEl = document.getElementById("l2");
var l = lEl.options[lEl.selectedIndex].value;
google.script.run.updateLarge(q, l);
}
</script>
If I misunderstand your question, I'm sorry.
Related
I've been banging my head against this for the past several days and have finally broken down and admitted defeat. This is my first project utilizing Google HTML Service, and what I'm trying to do seems simple, but I can't get it to work. Here is what I want to happen...
User interacts with spreadsheet and needs to add additional rows with data
User selects an option from a custom menu item (got this working)
This selection launches an HTML service form (got this working)
User selects the values from two drop down lists and clicks submit
The selected options read read (working kind of...) and passed to the .js (this is where I'm stuck), which will create the rows and place the data.
Below is my code:
Function that launches the HTML Service
function AddAdditionalApplicant() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('index');
ss.show(html);
}
index.html
<form name="AddApplicant" onsubmit="formSubmit()">
<p><b>What Type?</b></p>
<select name="NumOfApp" id="NumOfApp">
<option value="1">1</option>
<option value="2">2</option>
<option value="Cosigner">Cosigner</option>
</select>
<p><b>How Many?</b></p>
<select name="TypeOfApp" id="TypeOfApp">
<option value="Roommate">Roommate</option>
<option value="Cosigner">Cosigner</option>
</select>
<p></p>
<div>
<!--<input type="submit" class="button redButton" value="Submit" onclick="formSubmit()">-->
<input type="submit" class="button redButton" value="Submit">
</div>
</form>
<script type="text/javascript">
function formSubmit() {
//var a=document.getElementById('NumOfApp').selectedIndex;
//var b=document.getElementById('NumOfApp').options;
//alert("Index: " + b[a].index + " is " + b[a].text);
//var x=document.getElementById('TypeOfApp').selectedIndex;
//var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
google.script.run.getValuesFromForm(document.forms[0]);
}
</script>
If you uncomment the lines that are commented out you will see that the values are read correctly. Now, here is where it fails... I attempt to pass the form as an object to the function "getValuesFromFrom" using
google.script.run.getValuesFromForm(document.forms[0]);
Function getValuesFromFrom
function getValuesFromForm(AppForm){
Browser.msgbox("success") /attempt to test and see if the execution gets this far...no go
//var a=AppForm['NumOfApp'].selectedIndex;
//var b=AppForm['NumOfApp'].options;
//Logger.log(b[a])
//
//var x=AppForm.TypeOfApp.selectedIndex;
var type = AppForm.TypeOfApp.options[AppForm.TypeOfApp.selectedIndex].value;
Logger.log(type)
}
Nothing happens... the browser msgBox does not pop up. What am I missing? Also, how can I get the form to close automatically when the "Submit" button is pressed. Any help is greatly appreciated.
EDIT:
After going back and forth with #Sandy Good I realized the "AppForm" variable in the getValuesFromForm function was undefined, which means that the form object was not being passed to the function from the html. I tried another approach, and just attempted to pass a string variable to the function by altering the script portion of the html code like this
var x=document.getElementById('TypeOfApp').selectedIndex;
var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
var type=y[x].value
// google.script.run.getValuesFromForm(y[x], b[a]);
google.script.run.withFailureHandler(google.script.host.close)
.getValuesFromForm(type);
This was successful, while this...
var x=document.getElementById('TypeOfApp').selectedIndex;
var y=document.getElementById('TypeOfApp').options;
//alert("Index: " + y[x].index + " is " + y[x].text);
var type=y[x]
// google.script.run.getValuesFromForm(y[x], b[a]);
google.script.run.withFailureHandler(google.script.host.close)
.getValuesFromForm(type);
was not!
So the question remains, what was I doing wrong previously?
EDIT: July 10th...Working code
Function that launches the HTML Service
function AddAdditionalApplicant() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('index');
ss.show(html);
}
index.html
<form name="AddApplicant" onsubmit="formSubmit(this)">
<p><b>How Many?</b></p>
<select name="NumOfApp" id="NumOfApp">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<p><b>What Type?</b></p>
<select name="TypeOfApp" id="TypeOfApp">
<option value="Roommate">Roommate</option>
<option value="Cosigner">Cosigner</option>
</select>
<p></p>
<div>
<!--<input type="submit" class="button redButton" value="Submit" onclick="formSubmit()">-->
<input type="submit" class="button redButton" value="Submit">
</div>
</form>
<script type="text/javascript">
function formSubmit(argTheFormElement) {
google.script.run
.withFailureHandler(myFailureFunction)
.withSuccessHandler(google.script.host.close)
.getValuesFromForm(argTheFormElement);
}
function myFailureFunction(argError) {
alert("There was an error: " + argError.message);
google.script.host.close();
}
</script>
Function that receives the Form element
function getValuesFromForm(AppFormElement){
var ss = SpreadsheetApp.getActive();
var s = ss.getActiveSheet();
var sname = s.getName();
var num = AppFormElement.NumOfApp
var type = AppFormElement.TypeOfApp
var activeRow = s.getActiveCell().getRow();
var addCell = s.getRange(activeRow,2);
if (type == "Roommate") {
for(var i = 0; i < num; ++i){
AddRoommate(activeRow,addCell,sname,s);
}
}else if (type == "Cosigner"){
for(var i = 0; i < num; ++i){
AddCosigner(activeRow,addCell,sname,s);
}
}
s.setActiveRange(addCell.offset(1,1));
}
Hope this helps someone out!!!
Change your form tag, and add this to the function:
onsubmit="formSubmit(this)"
Then modify your function:
function formSubmit(argTheFormElement) {
Then put the variable argTheFormElement into the google.script.run.function(parameter);
google.script.run.getValuesFromForm(argTheFormElement);
That will pass all input values to the server. The get the values out, you must use the name of the name tag.
var type = AppForm.NumOfApp; //Get NumOfApp value
To make the dialog close, use:
google.script.host.close;
google.script.host.close
I have this problem today, I wanted my selected option would be the default value upon refresh of my page. For example I have this:
<select id="options">
<option value="0">Apple</option>
<option value="1">Orange</option>
<option value="2">Mango</option></select>
the default on my UI is Apple, so what I want is when I clicked Orange option it will be the default value when I refresh the page. Is there a way to do this? Thanks
I think local storage can help to you.
So for example:
<select id="options">
<option value="0">Apple</option>
<option value="1">Orange</option>
<option value="2">Mango</option></select>
Javascript
$("#options").on("change", function(){
var val = $(this).val();
// save to local
if(window.localStorage){
window.localStorage.setItem("#options-val", val);
}
});
if(window.localStorage){
var item = window.localStorage.getItem("#options-val");
if(item) $("#options").val(item);
}
And see demo
All your js code must be inside $(document).ready()
After run code on demo, try to reload page and you will see the result!
use onchange to set a session cookie then set option.slected when the page loads
<select id="options" onChange="document.cookie='fruit='+this.value;">
<option value="0">Apple</option>
<option value="1">Orange</option>
<option value="2">Mango</option></select>
<script type="text/javascript">
<!--
function getCookie(cname)
{
/* http://www.w3schools.com/js/js_cookies.asp */
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
// var c = ca[i].trim(); // trim not supported on IE8
var c = ca[i].replace(/^\s+|\s+$/gm,'');
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
window.onload = function() {
var v = getCookie('fruit');
if (v) document.getElementById('options').options[v].selected = true;
}
//-->
</script>
Set selected="selected" for the option you want to be the default.
<option selected="selected">
default
</option>
I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>
I have select box with default value,i want to retrieve default value and changed value using javascript,Below is my Html Select box:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST()">
<OPTION ID="1" VALUE="TEST1" SELECTED/>
<OPTION ID="2" VALUE="TEST2"/>
</SELECT>
Regards,
Raj
You can set custom attribute of the element in the onload event of the document:
window.onload = function() {
var oDDL = document.getElementById("TEST");
oDDL.setAttribute("default_value", oDDL.value);
};
Then to read it:
function Test() {
var oDDL = document.getElementById("TEST");
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Complete code and test case: http://jsfiddle.net/yahavbr/MbnH7/
Edit: to support more than one drop down, first pass reference in the onchange event like this:
<select id="TEST" name="TEST" onchange="Test(this);">
Then set the custom attribute in a loop:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("default_value", oDDL.value);
}
};
And the test function also need minor change as it's not getting the drop down as argument:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Updated test case: http://jsfiddle.net/yahavbr/MbnH7/1/
Edit II: to show the previously selected value some name changes are required, plus storing the value every time it's changing. The onload becomes this:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("previous_value", oDDL.value);
}
};
(Only change is the custom attribute name)
And the function becomes:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strPreviousValue = oDDL.getAttribute("previous_value");
alert("Previous value is: " + strPreviousValue + "\n Current value is: " + strCurrentValue);
oDDL.setAttribute("previous_value", strCurrentValue);
}
(Name change plus setting the custom attribute)
Updated and hopefully final test case: http://jsfiddle.net/yahavbr/MbnH7/4/
why not have the onfocus event (vs. onload) store the current value. one solution might be to do something like this:
$(t).data("prev",$(t).val())
and then have the onchange use that:
var oldVal = $(t).data("prev");
thus when someone clicks on, or tabs into, the ui element it stores the current state, and then can use that if there is a resulting change. also it would need to change the value if the change was accepted so that if focus was not changed (ie: they stayed in the pulldown and changed the value again) and they changed their mind and chose another option that the state was preserved.
many of the examples that i have seen of this store state in a that seemed to be vulnerable to change/events elsewhere.
HTML:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST(this)">
<OPTION ID="1" VALUE="TEST1" SELECTED>TEST 1</OPTION>
<OPTION ID="2" VALUE="TEST2">TEST 2</OPTION>
</SELECT>
javascript:
// store currently selected value
var previousValue = document.getElementById('TEST').value;
function TEST(e) {
alert('old value = ' + previousValue);
alert('new value = ' + e.value);
// store new value
previousValue = e.value;
}
example here
EDIT - I answered wrong before - Here's a sample HTML page that does it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
function showOptionValue(oSelect) {
var def;
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected){ //this option's defaultSelected property is set to true (from HTML: selected="selected")
def = oSelect[i].text; //or .value
}
var sel;
sel = oSelect[oSelect.selectedIndex].text;
alert (sel + ' : ' + def);
}
function resetSelect(oSelect) {
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected) //this option's defaultSelected property is set to true (from HTML: selected="selected")
oSelect.options[i].selected = true; //so, set its selected property to true, selecting it
showOptionValue(oSelect); //reset status
}
</script>
</head>
<body>
<form>
<!-- call handler function, pass Select object (represents drop-down list) -->
<SELECT NAME="cbo" onchange="showOptionValue(this)">
<OPTION VALUE="not_default">Not DEFAULT VALUE</OPTION>
<OPTION VALUE="1">Small</OPTION>
<!-- default value, preselected -->
<OPTION VALUE="2" selected="selected">Medium</OPTION>
<OPTION VALUE="3">Large</OPTION>
</SELECT>
<!-- call handler function, pass Select object using its name as a variable -->
<input type="button" value="Reset Drop-down" onclick="resetSelect(cbo)">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script type="text/javascript">
function fn(){
var select = document.getElementById("selectbox");
alert(select.options[select.selectedIndex].value)
}
</script>
</head>
<body>
<header style="margin-left: 50%;">Welcome</header>
<select id="selectbox">
<option value="number 01">Number 01</option>
<option value="number 01">Number 02</option>
<option value="number 01">Number 03</option>
<option value="number 01">Number 04</option>
</select>
<button style="margin-top:10px; margin-left:15px;" onclick="fn()">Click me</button>
</body>
</html>
This was interesting. In a select dropdown, trying not to use jQuery (with the exception of easing some of my pain on recreation), I ran into an issue that doesn't properly let any current browsers catch the proper selected option. Here is my code, for the page that recreates the issue (remember, no jQuery to necessarily solve issue, but more or less just telling me what I am doing wrong.
This one has me stumped.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
var options = new Array();
for ( var i = 0; i < 3; i++ ){
options.push(new Option("Option " + i, "Value" + i, false, false));
}
options[1].setAttribute("selected", "selected");
for ( var option in options ){
select_element.appendChild(options[option]);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
The html this creates is:
<select id="some-id" name="some-name">
<option value="Value0">Option 0</option>
<option value="Value1" selected="selected">Option 1</option>
<option value="Value2">Option 2</option>
</select>
But the anomaly here is that (in firefox at least), the selected option ends up being Option 0, which isn't the selected DOM element. In IE6, this select dropdown doesn't work at all.
There is an alternate method that does work, which includes piecing the options together manually, which works in all browsers that I have tested.
A small change made it work for me in Firefox:
...
//options[1].setAttribute("selected", "selected");
options[1].selected = true;
...
I'm manipulating the DOM element's attributes directly. Not sure why your method doesn't work. Maybe you should keep both lines so that the HTML generated has the selected = "selected" in it.
some old thread - however try something like this:
var idx=0;
while(obj.options[idx]) {
if(obj.options[idx].value==value) obj.options[idx].setAttribute('selected',true);
else obj.options[idx].removeAttribute('selected');
idx++;
}
Use selectedIndex to set the selected index of a select object.
options.selectedIndex = 1;
Here is the working code, which seems like more of a Hack!
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
for ( var i = 0; i < 3; i++ ){
var option_element = document.createElement('option');
option_element.setAttribute('value', "Value" + i);
option_element.appendChild( document.createTextNode( "Option " + i ) );
if (i == 1){
option_element.setAttribute("selected", "selected");
}
select_element.appendChild(option_element);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
options[1].setAttribute("selected", "selected");
is likely where your issue lies. The output you're getting is:
<option value="Value1" selected="selected">Option 1</option>
and the standard is:
<option value="Value1" selected>Option 1</option>
You may be able to do:
options[1].selected = true;