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
Related
I created a Select Element which creates Checkbox dropdown elements based on the items on the Google sheet.
Here is my HTML code:
<div class="form-row">
<div class="multiselect form-group">
<div class="selectBox" onclick="showCheckboxes()">
<select class="form-control" >
<option>Select an option</option>
</select>
<div class="overSelect" ></div>
</div>
<div id="checkboxes">
</div>
</div>
Here is my javascript code:
<script>
document.addEventListener("DOMContentLoaded", afterLoad);
document.getElementById("checkboxes").addEventListener("change", loadDisplayPos);
function afterLoad(){
google.script.run.withSuccessHandler(loadPosApp).checkPosApp();
}
function loadPosApp(postOpen){
postOpen.forEach(function(r){
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = r[0];
var label = document.createElement('label')
label.appendChild(checkbox);
label.appendChild(document.createTextNode(" " + r[0]));
var content = document.getElementById('checkboxes');
content .appendChild(label);
});
}
function loadDisplayPos(){
var contentCheck = document.getElementById('checkboxes').value;
console.log(contentCheck);
}
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
</script>
Here is my Google Apps Script function:
function checkPosApp()
{
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("VacantPositions_Data");
//const myDates = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
var postOpen = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
Logger.log(postOpen)
return postOpen;
}
Upon the load of the Web App, it will load the values from the Google sheet to the Web App as dropdown checkboxes. My problem is how to display the checked items to the Select Element as selected. I tried to get the value of the element ID "checkboxes" but it says undefined. Do you have any suggestions or advice? I am still trying to look for a solution. Thank you in advance for the help.
I got the idea on how to answer my problem in this link: https://www.dyn-web.com/tutorials/forms/checkbox/group.php. I just modified it in a way that I could get all the checked/ selected in an array then display it in the Web App
Here is the modified function in javascript.
function loadDisplayPos(){
var element = document.getElementById('checkboxes');
var tops = element.getElementsByTagName('input');
var tags = [];
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
if (tops[i].checked){
tags.push( tops[i].value);
}
}
}
var selectedPost = document.getElementById('posapp').innerHTML= tags;
}
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 am making hybrid app using Angular JS, wherein there is an page which has two dropdown (select controls).
The thing should be,When I select the first dropdown the second one automatically should fill based on the data fetched on change of first doropdown; but what happens is on change of first dropdown the data is fetched but it is not getting bind to second dropdown immediately though the model of second dropdown gets the data fetched on selection of first dropdown, instead what happens is when i again change the first dropdown selection, the previous data gets bind to the second dropdown.
Below is my code for the same -
Car Make dropdown -
<select name="make"
ng-options="item.MakeId as item.Make for item in memberdetailData.VehicleData"
ng-model="memberdetailData.selected_Make_ID"
ng-change="vehiclemakeselected()">
Car Model Dropdown -
<select name="model" ng-disabled="memberdetailData.selected_Make_ID === {}"
ng-options="item.ModelId as item.Model for item in memberdetailData.Vehicle_Model"
ng-model="memberdetailData.selected_Model"></select>
Controller code -
$scope.vehiclemakeselected = function () {
console.log($scope.memberdetailData.selected_Make_ID);
//console.log($scope.memberdetailData.selected_Make_ID);
db_factory.selectVehicleMasterData('select ModelId,Model from tbl_vehicle WHERE MakeId ="' + $scope.memberdetailData.selected_Make_ID + '";', function (res) {
console.log("this is respo");
//console.log(res);
$scope.memberdetailData.Vehicle_Model = null;
$scope.memberdetailData.Vehicle_Model = res;
console.log($scope.memberdetailData.Vehicle_Model);
// console.log($scope.memberdetailData.Vehicle_Model);
$scope.memberdetailData.selected_Model = null;
$scope.memberdetailData.selected_Model = $scope.memberdetailData.Vehicle_Model[0].ModelId;
}, function () {
// globalFactory.showAlert('Data Error', 'No Salutation Master Found, Kindly Sync Salutation Master');
});
}
DBFactory -
db_factory_obj.selectVehicleMasterData = function (query, callBack, errorcall) {
var result = [];
db_factory_obj.db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, rs) {
for (var i = 0; i < rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
MakeId: row['MakeId'],
Make: row['Make'],
ModelId: row['ModelId'],
Model: row['Model']
}
}
////console.log(result);
callBack(result); // <-- new bit here
}, errorcall);
});
}
Please help.
Thanks.
Krunal
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>
Hi I am trying to populate country and state dropdown list in dropdowns using jquery.
My json looks like this
Blockquote
var myjson = [{"countryName":"Afghanistan","countryCode":"AF"},{"countryName":"United States","countryCode":"US" ,"state":["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]},
{"countryName":"United States Minor Outlying Islands","countryCode":"UM"},
{"countryName":"Uruguay","countryCode":"UY","state":["abc","edf"]}];
My html
<body>
<select id = "country" name = "country" onchange= "getvalue()"></select>
<select id = "state" name = "state" onchage="getstate()"></select>
</body>
My javascript
<script>
function getvalue(){
var country = document.getElementById("country").value;
var divtemp = document.getElementById("test");
for (var i = 0; i < myjson.length; i++ ) {
if(myjson[i].state != null )
{
if(myjson[i].state.length==0){
$("#state").empty();
}
else
{
for(var j = 0 ; j< myjson[i].state.length;j++)
{
if(country === myjson[i].countryName)
{
//alert(country);
//alert(myjson[i].countryName);
//divtemp.innerHTML= myjson[i].state[j] + "<br>"+divtemp.innerHTML;
$("#state").append(
$("<option></option>")
.text(myjson[i].state[j])
);
}
}
}
}
}
</script>
This script function is populating states but when I select a another country the sates are appending to the earlier states list. I am not able to make out the changes required for my condition. I dont want to use Ajax to do this.
Try this.
In the head do this...
<script>
$(document).ready(
//when the document is loaded, initialize my selectors
function initCountries(){
//put all countries into the country selector
for (cix in myjson){
var options='<option value="'+cix+'">'+myjson[cix].countryName+'</option>';
$("#country").append(options);
}
//listen for the change event when the user chooses a country
$("#country").change(function fillStates(){
//find the country the user chose, then fill the states selector
var cix=$(this).val();
var states=myjson[cix].state;
$("#state").empty();
for (six in states){
var options='<option value="'+states[six]+'">'+states[six]+'</option>';
$("#state").append(options);
}
});
//listen for the change event when the user chooses a state
$("#state").change(function stateSelected(){
//show the state the user chose
var six=$(this).val();
alert(six);
});
});
</script>
and in your body change the selectors like this...
<select id = "country"></select>
<select id = "state"></select>
Clear state combobox on change of country..
document.getElementById('state').innerHTML = "";