Unable to populate dropdowns dynamically using angularJs - javascript

I have 3 dropdowns, A, B, C.
Based on dropdown A selection, dropdown B will be filled.
Then based on dropdown B selection, dropdown C will be filled.
I am able to achieve first 2 steps. But I am unable to achieve third point.
jsfiddle link

What about
<div data-ng-app data-ng-controller="myCtrl">
<select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
</select>
<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
</select>
<select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length'>
</select>
</div>
function myCtrl($scope) {
$scope.options1 = option1Options;
$scope.options2 = []; // we'll get these later
$scope.options3 = [];
$scope.getOptions2 = function() {
$scope.options2 = option2Options[option1Options.indexOf($scope.option1)];
$scope.getOptions3();
};
$scope.getOptions3 = function() {
var mergedOptions2=[].concat.apply([], option2Options )
$scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
}
}
Working fiddle

You are unable to achieve third point because you are trying to do that when dropdown A has a value, not B. If you add a new trigger on B, with the same functionality related to B, it will work.
Step 1: Add change trigger to your dropdown:
<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
Step2: Add a function on your controller to update options for dropdown C:
$scope.getOptions3 = function() {
var key2 = $scope.options2.indexOf($scope.option2);
var myNewNewOptions = option3Options[key2];
$scope.options3 = myNewNewOptions;
};
I've updated your fiddle accordingly: http://jsfiddle.net/Xku9z/1196/

You have forget to call getOption2() function for fetching option3
<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions2()">
</select>
Fiddler
http://jsfiddle.net/Xku9z/1198/

If I were you I would change your drop downs to call different functions. That way you aren't setting the third set of options before you need to.
Verified it works on JSFiddle.
Instead of..
function myCtrl($scope) {
$scope.options1 = option1Options;
$scope.options2 = []; // we'll get these later
$scope.options3 = [];
$scope.getOptions2 = function() {
var key = $scope.options1.indexOf($scope.option1);
var key2 = $scope.options2.indexOf($scope.option2);
var myNewOptions = option2Options[key];
var myNewNewOptions = option3Options[key2];
$scope.options2 = myNewOptions;
$scope.options3 = myNewNewOptions;
};
}
Use this...
function myCtrl($scope) {
$scope.options1 = option1Options;
$scope.options2 = []; // we'll get these later
$scope.options3 = [];
$scope.getOptions2 = function() {
var key = $scope.options1.indexOf($scope.option1);
var myNewOptions = option2Options[key];
$scope.options2 = myNewOptions;
};
$scope.getOptions3 = function() {
var key2 = $scope.options2.indexOf($scope.option2);
var myNewNewOptions = option3Options[key2];
$scope.options3 = myNewNewOptions;
};
}
And make sure you call data-ng-change="getOptions3()" on your second select tag.

Related

How to populate dropdown list at selection element with values from Google sheet?

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

Only first element is visible in Dynamic Dropdown list

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

Update the select options with given dynamic data

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 have two onchange methods and two values I need to pass

function changeHiddenInput(cLeague, nLeague) {
console.log(cLeague);
console.log(nLeague);
var objHidden1 = document.getElementById("hiddenInput1");
var objHidden2 = document.getElementById("hiddenInput2");
objHidden1.value = cLeague.value;
objHidden2.value = nLeague.value;
var a = objHidden1.value;
var b = objHidden1.value;
result.innerHTML = a + b;
}
<select class="form-control" id="currentleague" onchange="document.getElementById('currentleague').src=this.value; changeHiddenInput(select)">
<option value="rankicons/bronze5.png" (another value goes somewhere in here)>Bronze V</option>
</select>
Basically the first onchange changes the image in value, the second onchange passes in a value and does some math. Is there an alternative I could use to value or could I somehow pass in two values and somehow tell them apart?
You can have 2 values within the value property:
<option value="rankicons/bronze5.png,value nr 2">...</option>
Sample:
function changeHiddenInput(league) {
var league_values = league.split(",");
var objHidden1 = document.getElementById("hiddenInput1");
var objHidden2 = document.getElementById("hiddenInput2");
objHidden1.value = league_values[0];
objHidden2.value = league_values[1];
var a = objHidden1.value;
var b = objHidden1.value;
result.innerHTML = a + b;
// remove comment and set uniqe id to set img element src
//document.getElementById('img_id').src=league_values[0];
}
HTML:
<select class="form-control" id="currentleague" onchange="changeHiddenInput(this.options[this.selectedIndex].value)">
<option value="rankicons/bronze5.png,value nr 2">...</option>
</select>
The value document.getElementById('currentleague').src=this.value; I removed as it referenced the select element itself (same id) and added it to your function instead.

jquery function select custom attribute from select box

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

Categories

Resources