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
I am trying to have a dependent Dropdown list, Districts based on the value of selected State. But my code is rendering only the first element of the dynamic dropdown list.
<div class="input-field col s3">
<select id="nativeDistr">
<option value="" disabled selected>
Native District
</option>
</select>
<label>Destination District</label>
;
Appscript Code Snippet.
function getDistricts(state) {
Logger.log("Selected State=" + state);
var fileName = "states-and-districts.json";
var files = DriveApp.getFilesByName(fileName);
try {
if (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var json = JSON.parse(content).states_districts;
for (var i = 0; i < json.length; i++) {
if (json[i]["state"] === state) {
var districts = json[i]["districts"];
}
}
}
var optList = generateOptions(districts);
Logger.log(optList);
return optList;
} catch (err) {
return "Error getting data";
}
}
Javascript code
<script>
document.getElementById("nativeState").addEventListener("change", getDistr);
function getDistr() {
var state = document.getElementById("nativeState").value;
console.log("state scriptt:" + state);
google.script.run.withSuccessHandler(updatedistricts).getDistricts(state);
}
function updatedistricts(districts) {
console.log("From districts:" + districts);
var nativeDistr = document.getElementById("nativeDistr");
nativeDistr.innerHTML = districts;
M.updateTextFields();
} // When user selects the state the valuee off the state should get registered for district search
Blockquote
Durin execution I am getting the complete list of dynamic dropdown but while rendering the page only the first element is getting displayed.
Blockquote
M.updateTextFields() do not update dynamic dropdown, it updates the text fields. So there is a need to store a global reference to materialize select box to initialize it, post that there is a need to destroy that instance, and then reinitialize the select box again.
<script>
document.addEventListener("DOMContentLoaded", function () {
var elems = document.querySelectorAll("select");
var instances = M.FormSelect.init(elems);
});
document.getElementById("nativeState").addEventListener("change", getDistr);
function getDistr() {
var state = document.getElementById("nativeState").value;
google.script.run.withSuccessHandler(updatedistricts).getDistricts(state);
}
function updatedistricts(distrList){
nativeDistr.innerHTML = distrList;
var subcatSelectElem = document.querySelectorAll("select");
var subcatSelectInstance = M.FormSelect.init(subcatSelectElem, {});
}
Credit for soln.: Chicago Computer Classes
I am trying to create an online form using Netsuite.
We have a set for predefined fields like firstname, lastname, etc.
In the same we have a
NLSUBSCRIPTIONS
tag but the field type by default is drop down with multiple select option.
How can I change this drop down to a checkbox?
If you use a custom template you can hide the drop-down and iterate its options to create your own checkboxes.
e.g.
<div class="regFieldWrap">
<span class='cbExpand hideNsLabel'><NLCUSTENTITY_LIST_FIELD></span><input class="otherShadow valid" type="text" name="custentity_list_field_other"><span class="multiProto cbHolder"><input type="radio" name="custentity_list_field"><label class="cbLabel"></label></span>
</div>
and then
<script>
jQuery(function($){
// convert multi select to checkbox
$("span.multiProto").each(function(){
var proto = this;
var selName = $(proto).find("input").attr("name");
var otherCB = null;
$("select[name='"+selName+"']").css({display:'none'}).each(function(){
var sel = $(this);
var isReq = sel.hasClass('inputreq');
if(isReq) sel.removeClass('inputreq');
sel.find("option").each(function(){
if(!this.value) return;
var newby = $(proto.cloneNode(true));
var cb = newby.find("input").val(this.value);
if(isReq) cb.addClass('cb_selectone');
newby.find("label.cbLabel").text(this.text);
$(newby).removeClass('multiProto');
if((/\bother\b/i).test(this.text)){
var otherField = $("input.otherShadow[name='"+ selName+"_other']").each(function(){
var newOther = this.cloneNode(true); // strange but it gets around an IE issue
$(this).remove();
$(newby).find("input").data("conditionalOther", newOther);
newby.get(0).appendChild(newOther);
});
otherCB = newby;
} else proto.parentNode.insertBefore(newby.get(0), proto);
});
sel.get(0).options.length = 0;
});
if(otherCB) proto.parentNode.insertBefore(otherCB.get(0), proto); // make sure this is the end element
});
});
I am trying to load the first available option to the third drop-down.
The code is as below.
var categories = [];
categories["startList"] = ["C.","C#.","D.","Eb.","E.","F.","F#.","G.","Ab.","A.","Bb.","B."]; // Level 1
categories["C."] = ["C","C7","Cm","Cm7","Cmaj7","Csus4","Caug","Cdim"];
categories["C"] = ["032010","335553","133211","543210",""];
var nLists = 3; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function init() { fillSelect('startList',document.forms[0]['List1']);
fillSelect('startList',document.forms[0]['List4']);
fillSelect('startList',document.forms[0]['List7']);
}
navigator.appName == "Microsoft Internet Explorer"
? attachEvent('onload', init, false)
: addEventListener('load', init, false);
function getValues() {
var str = '';
for(i = 1; i < 6; i++) {
document.createElement('select')
str += document.getElementById('List' + i).value+'\n';
document.getElementById('creation').innerHTML=""; }
}
<select name='List4' id="List4" onchange="fillSelect(this.value,this.form['ch2'])"><option selected></option></select>
<select name='ch2' id="ch2" onchange="fillSelect(this.value,this.form['tb2'])"><option selected></option></select>
<select name='tb2' id="tb2"><option selected></option></select>
<input id="f2" type="text" size="1" value=1 class=copystuff>
<button onclick="do2()">Do2</button><br>
Now the problem is that when I try to select the second drop down menu "ch2", I want the first value to be loaded automatically in the third dropdown "tb2" according to the selection that I make in the second menu. For eg, if I select C. in the first menu, C in the second menu, I want 032010 to be already selected in the next menu. Is there any simple way to do this?
I have changed your code up a good bit. But I think it's a bit more readable, and may be easier to extend to more forms, categories, and selects.
First here is the working JSFiddle: http://jsfiddle.net/z1sw2bfq/
Second, here is the Fiddle code. Please see the comments for additional context.
<script>
//create a blank object to hold the select lists
var lists = { };
//create an object to hold the categories text arrays
var categories = {
"startList": ["C.","C#.","D.","Eb.","E.","F.","F#.","G.","Ab.","A.","Bb.","B."], // Level 1
"C.": ["C","C7","Cm","Cm7","Cmaj7","Csus4","Caug","Cdim"],
"C": ["032010","335553","133211","543210",""]
};
function init() {
//load the SELECT element from the form into lists
//Get all of the selects in forms[0]...
var selects = document.forms[0].getElementsByTagName("select");
for (var i in selects) {
//...and load those into lists.
lists[selects[i].id] = selects[i];
//Ex: creates a property like "lists.List4" also referenced by "list['List4']")
// which equals the select element with id List4
}
//enter the list name and the select id
fillSelect('startList', 'List4');
}
function fillSelect(currCatName, currListName){
//get the category
var cat = categories[currCatName];
//verify the category is valid
if (cat) {
//get the select
var select = lists[currListName];
//verify the select is valid
if (select) {
//clear the select
for (var i = select.options.length-1; i>=0; i--)
select.remove(i);
//check the data-first attribute
var datafirst = select.getAttribute("data-first");
if (datafirst == "blank") {
var opt = document.createElement('option');
opt.value = "";
opt.text = "";
select.add(opt);
}
//load the select
for (var j in cat) {
var opt = document.createElement('option');
opt.value = cat[j];
opt.text = cat[j];
select.add(opt);
}
}
}
}
//best to use feature detection instead of browser detection
if (window.attachEvent)
window.attachEvent('onload', init, false);
else
window.addEventListener('load', init, false);
</script>
<form action="#" method="get">
<!--
I added a "data-first" attribute to the selects. This will be used to determine if the
first option in the select is a blank or the first item in the list.
-->
<select name='List4' id="List4" onchange="fillSelect(this.value,'ch2')" data-first="blank"></select>
<select name='ch2' id="ch2" onchange="fillSelect(this.value,'tb2')" data-first="blank"></select>
<select name='tb2' id="tb2" data-first="first"></select>
</form>
I am trying to get the custom attribute values from the select box. It is triggered by a checkbox click which I already have working. I can get the name and value pairs just fine. I want get the custom attributes (therapy) (strength) (weight) and (obstacle) from the option value lines. is this possible?
select box
<option value="2220" therapy="1" strength="1" weight="0" obstacle="0">Supine Calf/Hamstring Stretch</option>
<option value="1415" therapy="0" strength="0" weight="0" obstacle="0">Sitting Chair Twist</option>
<option value="1412" therapy="0" strength="0" weight="0" obstacle="0">Static Abductor Presses</option>
jQuery
// exercise list filter category
jQuery.fn.filterByCategory = function(checkbox) {
return this.each(function() {
var select = this;
var optioner = [];
$(checkbox).bind('click', function() {
var optioner = $(select).empty().scrollTop(0).data('options');
var index=0;
$.each(optioner, function(i) {
var option = optioner[i];
var option_text = option.text;
var option_value = parseInt(option.value);
$(select).append(
$('<option>').text(option.text).val(option.value)
);
index++;
});
});
});
};
You need to find the selected , like this:
var $select = $('#mySelectBox');
var option = $('option:selected', $select).attr('mytag');
That is how to get selected option attribute:
$('select').find(':selected').attr('weight')
Get selected option and use attr function to get the attribute:
$("select").find(":selected").attr("therapy")
JSFIDDLE