Dynamically populate select options with nested JSON - javascript

What i want to achieve
I have got one static select html options, these options do not change but will determine what the other select boxes output.
<select id="firstselectbox">
<option value="first">This is the first</option>
<option value="second">This is the second</option>
<option value="third">This is the third</option>
<option value="fourth">This is the fourth</option>
<option value="fifth">This is the fifth</option>
</select>
Currently, the code i have written doesnt want to output the following:
Select 1: option selected first
Select 2: checks jSon file, finds first and all of the nodes (second layer) and list them. When a user selects that.
Select 3: displays the third layer
Please note the * is the option selected below - select 1 is static and select 2 and 3 are dynamic.
Select 1 Select 2 Select 3
first* London Famous Famous
second Jersey London Famous
third North*
fourth South East
fifth South West
sixth
What have i done so far
var datajson = {"first":[{"jesery":[{"id":"jesery","name":"Jesery","jesery":[{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"dontknow":[{"id":"dontknow","name":"Dont Know"}]}],"second":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}]}],"third":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"north":[{"id":"north","name":"North","north":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}]}],"forth":[{"north":[{"id":"north","name":"North","north":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"dontknow":[{"id":"dontknow","name":"Dont Know"}]}],"fifth":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"southeast":[{"id":"southeast","name":"South East","southeast":[{"id":"distance","name":"Distance"}]}]}]}
$("#firstselectbox").on('change', function() {
$("select#firstselectbox").html('');
var locations = datajson[$(this).val()];
var locationString = '';
$.each(locations, function(i, item) {
console.log(locations[i]);
locationString += '<option id="'+ locations[i].id + '" value="' + locations[i].id + '">' + locations[i].name + '</option>';
});
$('#secondselectbox').html(locationString);
});
Issue?
The following code is locationString += '<option id="'+ locations[i].id + '" value="' + locations[i].id + '">' + locations[i].name + '</option>'; is outputting unidentified.
However console.log(locations[i]); is outputting the array that that is selected from the static select box (first, second etc..). However, trying to separate that out seems to fail.
The current code is outputting unidentified.

Use unobtrusive JavaScript so you won't have to hunt bugs like this one:
$('#secondselectbox').empty()
$.each(locations, function(i, item) {
$("<option/>",{id:locations[i].id, value:locations[i].id, text:locations[i].name})
.appendTo('#secondselectbox')
})
Edit: Also there is a problem with your JSON structure. You basically have an array which contains a single object, so when you foreach the array you are at one level lower than where you need to be.

Related

How to update a dropdown list dynamically using JQuery?

I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
Try this solution:
$.each(items, function (i, value) {
$('#boardingDropdown').append($('<option>', {
value: value_value,
text : text_value
}));
});
The output should be something like this:
<select title="Select pickup city" id="boardingDropdown">
<option value="value_value">text_value</option>
</select>
Instead of:
let $boardingOption = $("<option>" + value + "</option>");
you should use:
let boardingOption= "<option>" + value + "</option>";
And in your code:
$(#boardingDropdown").append($boardingOption);
you missed a quote mark, it should be: $("#boardingDropdown")
Finally, according to my corrections, it should become:
$("#boardingDropdown").append(boardingOption);
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
<select title="Select pickup city" id="boardingDropdown">
</select>
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
<div>
<label>Boarding Point </label>
<div id="boardingDropdown"></div>
</div>
Then in the jquery, I appended the <select> tag as well:
$.getJSON(busApi, function (boardingPoints) {
let opt = '<select>';
$.each(boardingPoints, function (index, value){
opt += '<option value="' + index + '">' + value + '</option>';
});
opt += '</select';
$("#boardingDropdown").append(opt);
});
Now it is working as expected. :)

Issue with getting selected value of select menu in query?

There is a select menu in my page which loads the values from DB. I am able to view the values in select menu. but while displaying the selected value, I am not able to display it properly. i.e. If the value contains any spaces it is not getting full value( EX: if I selected "Wilson Garden", I am getting only "Wilson". It is displaying "Wilson Garden" in select box, when I try to get that value by on change event I got only "Wilson",Same thing happen for all the values which has space in it.
my html is code is:
<select name="select-choice-1" id="select-choice-1">
<option value="Select Category">Select Category</select>
</select>
And my Jquery code is as follows,
$("#select-choice").on('change', function(event) {
alert( this.value );
console.log("Category is: " +this.value); // Here I am getting the value..
});
// Store the values dynamically in to select menu..
$(document).on("pagebeforeshow","#homePage",function(){
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select distinct Category from Locationlog;", [], function (tx, res) {
for (var i = 0; i < res.rows.length; i++) {
$("#select-choice").append('<option value='+res.rows.item(i).Category+'>'+res.rows.item(i).Category+'</option>');
}
$("#select-choice").listview('refresh');
});
});
});
It because you didn't quote the attribute. You need to wrap those values around double quotes.
var opt = '<option value="';
opt += res.rows.item(i).Category;
opt += '">';
opt += res.rows.item(i).Category;
opt += '</option>';
$("#select-choice").append(opt);

Multiselect dropdown option value taking only one word

I have a multiselect dropdown inside a table
<td>
<select multiple="multiple" name="multiple" id="multiple" class="required">
</select>
</td>
The option values are populated with json data.
for(var i=0;i<jsonString.length;i++){
var name=jsonString[i].Name;
$('#multiple').append('<option value=' + name + '>' + name + '</option>');
}
When the user start selection i am trying to display each selected item inside a paragraph
<script>
function displayVals() {
var multipleValues = $("#multiple").val() || [];
$("p").html( " <b>Selected Properties:</b> " +
multipleValues.join(", "));
}
$("select").change(displayVals);
displayVals();
</script>
But in the paragraph i get just one word per selection, not the complete name. (Say If i select "some text" i get only "some"). Can somebody point out where is the error?
While populating with JSON data use
<option values= > instead of `<option value>
Working fine for me now.`

Dynamically adding element to Select and setting the selectindex in JQuery

I've created a dynamic select list box as below
for (var i in c) {
//alert(c[i].IsDefault);
if(c[i].IsDefault==true){
//alert('found default');
$("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
temp = c[i].Code;
}
else{
$("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
}
}
refreshed it
$('#AnsType').selectmenu('refresh');
I tried all these methods and tried to select teh 2nd element in teh listnone worked for me.
$('#AnsType').val(temp.toString());
$('#AnsType').get(3).selectedIndex = 3;
$('select#AnsType').val('3');
$("#AnsType option[text='3']").attr("selected","selected") ;
$("#mydropdownlist").attr('selectedIndex', 1);
$('#AnsType').val(3);
$("#AnsType").attr('selectedIndex', 2);
$("#AnsType").val(c[parseInt(temp)].Code);
$("select#AnsType option[selected]").removeAttr("selected");
$("select#AnsType option[value='"+temp+"']").attr("selected", "selected");
this is how when my listbox is created
<select id="AnsType" name="AnsType">
<option value="1">Obokad</option>
<option value="3">Egen bokning</option>
</select>
Any help is appreciated and thanks in advance for your help..
If you want some element to be pre-selected when creating the menu, add the selected attribute to the corresponding option element:
if(c[i].IsDefault==true){
$("#AnsType")
.append("<option value='" + c[i].ID + " selected='selected'">" + c[i].Code+ "</option>");
temp = c[i].Code;
}
Note that you have to refresh again the selectmenu after you programmatically change the value of the underlying select element:
$('#AnsType').val('3');
$('#AnsType').selectmenu('refresh');
Documentation
refresh update the custom select
This is used to update the custom select to reflect the native select element's value. If the number of options in the select are different than the number of items in the custom menu, it'll rebuild the custom menu. Also, if you pass a true argument you can force the rebuild to happen

Change form field options dynamically (and restore previously selected options) using jQuery

I'm fairly new to both jQuery and JavaScript so can anyone please point out what I'm missing here?
I have a form with multiple pairs of select fields, where the content of the second field relies on the selection of the first one.
Once a value is chosen from the first one then a piece of jQuery code empties the corresponding second select options, gets new values as JSON and inserts them as new select values. All of this works with the code I've written.
However if a user has chosen a second value, I'd like to restore it if possible (meaning if the new values also include the one previously selected).
I tried to do this by first saving the second value and then trying to set it once the new options have been inserted. This did not work. However when trying to debug I inserted an alert() just before restoring the second value and with that in there it does work...
Am I missing something very basic here? Any help would be appreciated.
HTML:
<select name="party-0-first" id="id_party-0-first">
<option value="" selected="selected">---------</option>
<option value="1">first_value1</option>
<option value="2">first_value2</option>
<option value="3">first_value3</option>
<option value="4">first_value4</option>
</select>
<select name="party-0-second" id="id_party-0-second">
<option value="" selected="selected">---------</option>
<option value="1">second_value1</option>
<option value="2">second_value2</option>
<option value="3">second_value3</option>
<option value="4">second_value4</option>
</select>
<select name="party-1-first" id="id_party-1-first">
...
JavaScript:
$.fn.setSecond = function() {
var divName = $(this).attr("name");
divName = divName.replace('-first', '');
divName = divName.replace('party-', '');
// Save the currently selected value of the "second" select box
// This seems to work properly
setValue = $('#id_party-' + divName + '-second').val();
// Get the new values
$.getJSON("/json_opsys/", { client: $(this).val() },
function(data){
$('#id_party-' + divName + '-second').empty();
$('#id_party-' + divName + '-second').append('<option value="" selected="selected">---------</option>');
$.each(data, function(i, item){
$('#id_party-' + divName + '-second').append('<option value="' + item.pk + '">' + item.fields.name + '</option>');
});
});
// Here I try to restore the selected value
// This does not work normally, however if I place a javascript alert() before
// this for some reason it does work
$('#id_party-' + divName + '-second').val(setValue);
$(document).ready(function(){
$('[id*=first]').change(function() {
$(this).setSecond();
});
});
Well, it looks like your getJSON() call is involved in that issue.
Remember, from the start, all ajax request are ASYNC, means your last line of code
there is most likely executed before the getJSON() success eventhandler is called.
When you set the variable "setValue", try declaring it with var:
var setValue = $('#id_party-' + divName + '-second').val();
But I don't think that's the problem. The problem is that you're trying to reset the value in some code that's going to run before the getJSON is actually done. Try moving the thing that sets the value inside the function that's passed to getJSON.
$.getJSON("/json_opsys/", { client: $(this).val() },
function(data){
$('#id_party-' + divName + '-second').empty();
$('#id_party-' + divName + '-second').append('<option value="" selected="selected">---------</option>');
$.each(data, function(i, item){
$('#id_party-' + divName + '-second').append('<option value="' + item.pk + '">' + item.fields.name + '</option>');
});
$('#id_party-' + divName + '-second').val(setValue);
});

Categories