I have a Google sheet with custom HTML form. The form contains <selection> element.
Like this
<select id="category_name" name="category_name" class="control" style="width:150px;height:20px;margin:10px 0 10px 0;">
<option value="" selected></option>
</select>
I'm getting values from the sheet
function getCategory() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getSheetByName(SHEET_NAME);
let list = sh.getRange(2, 1, sh.getLastRow() - 1).getValues();
return list;
}
And then I'm populating this selection with expected values in HTML file
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("category_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.val = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getCategory();
}());
It looks like list was populated well, but when I choice some item from selection it returns blank value after form submitting.
Where I'm wrong and how to fix it?
Issue:
You are not setting the <option> value correctly: val is not a valid attribute. Because of this, no value is added to each <option> and they are not submitted.
Solution:
Set the option value like this:
option.value = selectList[i][0];
Using Option constructor:
Of course, using the Option constructor would also work:
var option = new Option(selectList[i][0], selectList[i][0]);
Reference:
HTMLOptionElement
Option()
I use this a lot:
function updateSelect(vA,id){
var id=id || 'sel1';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);//Option(text, value);
}
}
new option
Need to send dynamic (not hardcode) data to a select element.
This code works great in one of my sheets but doesn't work in the other sheet.
The "select" element doesn't get updated with the options I send..
I don't get an error message either.
I've spent a lot of time twitching it and trying to find why but still don't see what's wrong.
p.s. I used a dummy object to send the data for testing purpose.
The html (used MaterializeCss framework)
<select class="icons browser-default" id="selName" onChange ="getNameText();">
<option value="" disabled selected>Choose week</option>
<div id = "err"></div>
//select element initialization in framework
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var options = handlers()
var instances = M.FormSelect.init(elems);
});
function handlers() {
var success = google.script.run.withSuccessHandler(addOptions).getNamesForDropdown()
var failure = google.script.run.withFailureHandler(showError).getNamesForDropdown()
return;
}
function addOptions(names) {
var selectTag = document.getElementById("selName") //select tag
for (var k in names) {
var thisID = k;
var thisText = names[k];
var option = document.createElement("option"); //creating option
option.text = thisText
option.value = thisID;
selectTag.add(option);
}
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
//get the text of selected option
function getNameText() {
var sel = document.getElementById("selName")
var nameText = sel.options[sel.selectedIndex].text;
return nameText;
}
Dummy object I send:
function getNamesForDropdown() {
var namesObj = {
one: "blah",
two: "blahblah"
}
return namesObj;
}
Here's the result what I get (on the screen you there's only hardcoded option):
I handled it. I added a class "browser-default" to the select and the options got updated. This class comes from MaterializeCss Framework.
I want to create a dynamic drop down list with javascript.
Right now it works like this:
- if I choose first option, then second, then third.
I want to change this code to:
- when I choose first option, it shows second and third option in the same time(second and third option depends of first)
I want to do something like:
Choose name:
John Doe(first option)
Choose proffesion:
Dentist(second option)
Choose gender:
male(third option)
Is it possible?
Thanks for reply.
<!doctype html>
<html>
<head>
<script>
var modelsArray = new Array(
["Chevy","","Camaro","Corvette","Impala"],
["Dodge","","Avenger","Challenger","Charger"],
["Ford","","Mustang","Shelby"]
);
var colorsArray = new Array(
["Camaro","","White","Black","Red"],
["Corvette","","White","Purple","Blue","Fawn"],
["Impala","","White","Black","Red","Chrome Yellow"],
["Avenger","","White","Acid Green","Alice Blue"],
["Challenger","","White","Violet","Blue-Green"],
["Charger","","White","Dark Pastel Red"],
["Mustang","","White","Debian red","Impala","Flame"],
["Shelby","","White","Deep Spring Bud"]
);
function populate1(s1,s2,s3){
var optionArray = [];
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
var s3 = document.getElementById(s3);
s3.innerHTML = "";
for(var i = 0; i < modelsArray.length; i++){
if(s1.value == modelsArray[i][0]){
for(var x = 1; x < modelsArray[i].length; x++){
optionArray.push(modelsArray[i][x]);
}
}
}
optionArray.sort();
for(var option in optionArray){
var newOption = document.createElement("option");
newOption.value = optionArray[option];
newOption.innerHTML = optionArray[option];
s2.options.add(newOption);
}
}
function populate2(s1,s2){
var optionArray = [];
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
for(var i = 0; i < colorsArray.length; i++){
if(s1.value == colorsArray[i][0]){
for(var x = 1; x < colorsArray[i].length; x++){
optionArray.push(colorsArray[i][x]);
}
}
}
optionArray.sort();
for(var option in optionArray){
var newOption = document.createElement("option");
newOption.value = optionArray[option];
newOption.innerHTML = optionArray[option];
s2.options.add(newOption);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate1(this.id,'slct2','slct3')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2" onchange="populate2(this.id,'slct3')"></select>
<hr />
Choose Car Color:
<select id="slct3" name="slct3"></select>
<hr />
</body>
</html>
I've created a jsfiddle here which implements a rudimentary example.
You can create DOM event listeners to respond to the change event of the select elements. When these events are triggered, pass the value of the selected option to a function which can extract the models/colours from the data.
Ideally you will setup your server side code to return the data in a format such as:
{
"makes": {
"ford": {
"models": {
"focus": {
"colours": [
"blue",
"black"
]
},
"probe": {
"colours": [
"green",
"grey"
]
}
}
}
}
Using this data format you can easily drill down the object tree e.g.
carData.makes.ford.models.focus.colours
Once you have the data you can then use jQuery to append options to your select e.g.
for (var model in models) {
$('select').append('<option value="'
+ model + '">' + model +
'</option>');
}
*EDIT: If you want to use the combination of the first two selects then you can do something like this:
var mapCombinations = {canada: {toronto: {mapName: "canada"}}};
var mapName = mapCombinations[selectValue1][selectValue2].mapName);
showMap(mapName);
function showMap(mapName) {
// Call server to get map
$.ajax({
type: "GET",
url: "http://yoururl.com/api/map/" + mapName,
success: function(data){
// display map
}
});
}
EDIT2: You can use the same principle if you want the third select to contain an action. I've replaced the colours array with actions. This third select will change depending on the first 2 select values.
Updated jsfiddle which doesn't use jquery.
You can then set up an event listener to process that action.
I need to repeat third value all the time.
I try to give you an example.
First value = Country
Second value = City
Third value = option
And I want to do something like:
If First value = Canada then Second value = Toronto
If First value = Canada then Third value = Show canada map
Second Value and third value don't depend of themselve, only of first value.
my html code.
<input type="button" onClick="show($row['empDesignation']?>');" value="update"/>
so when i click on update button m passing the value to javascript
<script type="text/javascript">
function show(desig){
document.getElementById("designation").value=desig;
}
</script>
so i want the value which is passed to javacript to be listed first in the dropdown list
php code
<select id="designation" name="designation">
<? while($role=mysql_fetch_array($sql_role)){ ?>
<option value="<?=$role['id']?>"><?=$role['id']?></option>
<? } ?></select>
<option value="<?php echo $role['id']?>"><?php echo $role['id']?></option>
You can do that like following algorithm;
Get your entire select options and put it in to array
Remove all options from selectbox
Put first option that you get from show function
Fill rest of the item from array to selectbox.
You can see an example below;
function show(desig) {
var arr = [];
var list = document.getElementById("designation");
for (var i = 0; i < list.options.length; i++) {
arr.push(list.options[i]);
}
// Delete all options from selectbox
list.options.length = 0;
// create first option
var opt = document.createElement('option');
opt.innerHTML = desig;
opt.value = desig;
list.appendChild(opt);
for (var j in arr) {
if (arr[j].value !== desig) {
var opt = document.createElement('option');
opt.innerHTML = arr[j].text;
opt.value = arr[j].value;
list.appendChild(opt);
}
}
}
You can see working demo here: http://jsfiddle.net/rZmgY/1/
I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.
Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.