JSON accessing array objects using a named index - javascript

Suppose I have this HTML
<form action="#" action="get">
<select name="college" id="college" onchange="selection('college', 'course')">
<option value="">Select an Option</option>
<option value="amity">Amity University</option>
<option value="indraprastha">Indraprasth University</option>
</select>
<br>
<select name="course" id="course" onchange="selection('course', 'stream')" >
<option value="">Select an Option</option>
</select>
<br>
<select name="stream" id="stream">
<option value="">Select an Option</option>
</select>
</form>
I have this JSON,
{
"amity":{
"course":[
{
"name":"B.Tech",
"value":"btech",
"stream":[
{
"name":"Computer Science",
"value":"cse"
},
{
"name":"Information Technology",
"value":"cse"
},
{
"name":"Aerospace Engg.",
"value":"cse"
}
]
},
{
"name":"M.Tech",
"value":"mtech",
"stream":[
{
"name":"Networking",
"value":"net"
},
{
"name":"telecommunications",
"value":"tc"
}
]
}
]
}
}
The Javascript is,
function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
var college = $('#college').val(),
cr = $('#course').val(),
st = $('#stream').val(),
se = $('#sem').val();
$.getJSON("json/select.json", function(data) {
switch(s1) {
case 'college':
$.each(data[college].course, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
case 'course':
$.each(data[college].course[].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
}
});
}
I am making a dynamic drop-down menu where the next drop down values are fetched from JSON object file, using the reference of previous values. As suggested from my this question (link), I am able to get the value of course (second drop-down) using the course array in the object.
Now, since the values in the second select menu(course) are filled dynamically, I can't figure out how to take the corresponding course array element to fill the next select menu options for stream array.
Since the course property in JSON is an array, I don't know which index element element is chosen from second menu (See the switch case for 'course', the data[college].course[] index is empty). The hardcoded [0] works, but that's not dynamic then.
How to access the stream array using the values of course grabbed from second menu.
I hope I am clear. Thanks in advance!

Just iterate through array of courses to get the stream dynamically:
for (var i = 0; i < data[college].course.length; i++) {
currentStream = data[college].course[i].stream;
}
I.e. using your code:
for (var i = 0; i < data[college].course.length; i++) {
$.each(data[college].course[i].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});
}
Finding the current stream for your selected course:
// assuming cr = "btech"
for (var i = 0; i < data[college].course.length; i++) {
if (data[college].course[i].value == cr) {
currentStream = data[college].course[i].stream;
break;
}
}
$.each(currentStream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});

function selection(s1, s2) {
var first = document.getElementById(s1),
second = document.getElementById(s2);
var college = $('#college').val(),
cr = $('#course').val(),
st = $('#stream').val(),
se = $('#sem').val();
$.getJSON("json/select.json", function(data) {
switch(s1) {
case 'college':
$.each(data[college].course, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}); break;
case 'course':
var course = data[college].course;
for(var i = 0;i<course.length;i++){
if(course[i].name === cr){ //cr is selected option
$.each(course[i].stream, function(key, value) {
second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
}
}
}); break;
}
});
}

Related

Get the selected value from populating select options

var regionOption = document.querySelector("#municipality");
var districtOption = document.querySelector("#districtName");
var provOption = document.querySelector("#region");
createOption(provOption, Object.keys(regions));
provOption.addEventListener('change', function() {
createOption(regionOption, regions[provOption.value]);
});
regionOption.addEventListener('change', function() {
createOption(districtOption, districts[regionOption.value]);
});
function createOption(dropDown, options) {
dropDown.innerHTML = '';
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
};
CSS:
<select id="region" style="width: 125px;"></select>
<select id="municipality" style="width: 125px;"></select>
<select id="districtName" style="width: 125px;"></select>
So, I'm populating options for an empty select and I was wondering how to get the value of the selected option. I basically want to check if (select value = 'A' && another selecte value = 'B') { do something}
Set the value attribute on each <option>:
<option value="' + value + '">
Then, simply check the value property on the <select>.
if (document.getElementById("region").value === 'A') {
// ...
}

Bind SELECT Element with an Array of objects using JavaScript

I am trying to populate a SELECT dropdown list with an array of objects using JavaScript and then display properties of that object based on the option selection. So far I have been able to populate the dropdown, however I can't seem to get the output correctly, as it only selects the last value in the for loop and hence only outputs the last object, for each selection. I thought this might be a closure issue, but I have gone through a lot closure solutions and none seem to work. How can I get each option selection to display the right object properties?
<html>
<body>
<input type="button" onclick="populateSelect()" value="Click to Populate SELECT" />
<!--The SELECT element.-->
<select id="sel" onchange="show()">
<option value="">-- Select --</option>
</select>
<p id="msg"></p>
</body>
<script>
// THE ARRAY.
var birds = [
{ID: 001, Bird_Name: "Eurasian Collared-Dove"},
{ID: 002, Bird_Name: "Bald Eagle"},
{ID: 003, Bird_Name: "Cooper's Hawk"},
];
function populateSelect() {
var ele = document.getElementById('sel');
for (var i = 0; i < birds.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
ele.innerHTML = ele.innerHTML +
'<option>' + birds[i]['Bird_Name'] + '</option>';
}
}
function show() {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
for (var i = 0; i < birds.length; i++)
{
msg.innerHTML = birds[i].ID + " " + birds[i].Bird_Name;
}
}
</script>
</html>
You should use a value for the options and pass that value into your event handler function. Then compare selected value to the elements in array as well as set a default if no value selected
var birds = [
{ID: 001, Bird_Name: "Eurasian Collared-Dove"},
{ID: 002, Bird_Name: "Bald Eagle"},
{ID: 003, Bird_Name: "Cooper's Hawk"},
];
function populateSelect() {
var ele = document.getElementById('sel');
birds.forEach(function(b) {
ele.innerHTML += '<option value="' + b.ID + '">' + b['Bird_Name'] + '</option>';
})
}
function show(id) {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
if (!id) {
msg.innerHTML = 'None selected';
} else {
for (var i = 0; i < birds.length; i++) {
if (Number(id) === birds[i].ID) {
msg.innerHTML = birds[i].ID + " " + birds[i].Bird_Name;
break;
}
}
}
}
populateSelect()
<select id="sel" onchange="show(this.value)">
<option value="">-- Select --</option>
</select>
<p id="msg"></p>
You should use the value attribute in tag, also as one of the comment mentions you can make use of the events too.
// THE ARRAY.
var birds = [{
ID: 001,
Bird_Name: "Eurasian Collared-Dove"
},
{
ID: 002,
Bird_Name: "Bald Eagle"
},
{
ID: 003,
Bird_Name: "Cooper's Hawk"
},
];
var select = document.getElementById('sel');
function populateSelect() {
for (var i = 0; i < birds.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
// add the value attribute in option as the id of bird
select.innerHTML = select.innerHTML +
'<option value=' + birds[i].ID + '>' + birds[i]['Bird_Name'] + '</option>';
}
}
function show() {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
// find the bird with the selected id
let selectedBird = birds.find(bird => bird.ID == select.value);
// display the info
msg.innerHTML = selectedBird.ID + " " + selectedBird.Bird_Name;
}
<html>
<body>
<input type="button" onclick="populateSelect()" value="Click to Populate SELECT" />
<!--The SELECT element.-->
<select id="sel" onchange="show()">
<option value="">-- Select --</option>
</select>
<p id="msg"></p>
</body>
</html>

Cascading Dropdown is not working using jquery

by the way i just got the js code from one of the questions here but i don't why it will not work on mine. please help me.
.js file
jQuery(function ($) {
var College = {
'College of Engineering': ['Civil Engineering', 'Computer Engineering', 'Electronics and Communication Engineering', 'Electrical Engineering', 'Industrial Engineering'],
}
var $College = $('#college');
$('#department').change(function () {
var department = $(this).val(), clg = College[department] || [];
var html = $.map(clg, function (cl) {
return '<option value="' + cl + '">' + cl + '</option>'
}).join('');
$College.html(html)
});
});
is my code wrong? i dont know why it will not work.
the html code for this is
<select class="form-control" name="college" id="college" runat="server">
<option value="College">Select College</option>
<option value="College of Engineering">College of Engineering</option>
<option value="CAS">College of Arts and Science</option>
<option value="Commerce">College of Commerce</option>
</select>
<select id="department" class="form-control" runat="server" placeholder="Department" >
<option value="Department">Select Department</option>
</select>
You could do something like this: https://jsfiddle.net/rockmandew/12ej2rt3/
Set your HTML Markup like so: (*this example contains a three step dropdown selection)
<select id="main_list">
<option value="default" selected>Select Your List</option>
<option value="mobile">mobile list</option>
<option value="laptop">laptop list</option>
</select>
<select id="brand" class="secondary"></select>
<select id="version" class="secondary"></select>
Then the JS as follows:
$(function() {
var sel, i,
list = ['mobile', 'laptop'],
phone = ['Samsung', 'Nokia'],
laptop = ['HP', 'Dell'],
android = ['4.1', '4.2'],
windows = ['8', '8.1'],
dev_default = '<option value="default" selected>Select your Device brand</option>',
os_default = '<option value="default" selected>Select your OS version</option>';
sel_brand = $('#brand');
sel_version = $('#version');
$('select').change(function() {
switch (this.id) {
case 'main_list':
$('.secondary').hide();
sel_brand.find('option').remove();
sel_brand.append(dev_default);
sel_brand.show();
if (this.value == 'mobile') {
for (i = 0; i < phone.length; i++) {
$("#brand").append(
'<option value="' + phone[i] + '">' + phone[i] + '</option>'
);
}
}else if (this.value == 'laptop') {
for (i = 0; i < phone.length; i++) {
$("#brand").append(
'<option value="' + laptop[i] + '">' + laptop[i] + '</option>'
);
}
}
break;
case 'brand':
sel_version.find('option').remove();
sel_version.append(os_default);
sel_version.show();
if (this.value == 'Samsung') {
for (i = 0; i < android.length; i++) {
$("#version").append(
'<option value="' + android[i] + '">' + android[i] + '</option>'
);
}
}else if (this.value == 'Nokia' || this.value == 'HP' || this.value == 'Dell') {
for (i = 0; i < windows.length; i++) {
$("#version").append(
'<option value="' + windows[i] + '">' + windows[i] + '</option>'
);
}
}
break;
}
});
}); //END document.ready()
Also, if you need/want more information on how to populate these dropdowns dynamically from either a text file, JSON, or a database - check out this article: https://css-tricks.com/dynamic-dropdowns/

Dropdown selected default to be the blank option

Iam using MVC4, initially my dropdown displays the list of data,
My javascript looks like,
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
How do i set the selected default to be the blank option.
html:
<div class="SmallTopSpace">
<span class="LabelNormal">Primary Case Agency</span>
#Html.DropDownListFor(m => m.Agencies.AgencyKey, new SelectList(""), "", new { #class = "ImportDropDownMax", #id = "OwnerAgency", #onchange = "OwnerAgencyFunction();" })
</div>
before the $.each just append at that start of the data array another empty element .
or in your html do :
<select>
<option disabled selected></option>
</select>
Can't you just insert an empty option at the top in your view/html?
<select id="OwnerAgency">
<option></option>
</select>
Or you can add it in javascript.
var emptyOption = true;
$.each(data, function (value, key) {
var opt;
if (emptyOption) {
opt = "<option></optino>";
$("#OwnerAgency").append(opt);
emptyOption = false;
}
opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
<select id="mySelect">
</select>
script:
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
mySelect.append('<option value=' + myOptions.length + ' selected>default</option>');
set your default select before or after select list generation http://jsfiddle.net/3ns3fj3t/
in your case:
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
$("#OwnerAgency").append('<option value=' + data.length + ' selected>default</option>');
You could do it in your C# ViewModel by adding an empty element to SelectList object:
var selectList = new SelectList(....);
selectList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
selectList.SelectedIndex = 0;

Issue With refresh / clear the select list for on change event in Jquery?

I have two select boxes in my application, based on first select box selected value, the second select box values will display from DB. Now the issue is If I select one value in first select box the respective values will shown in second select box, again I change the value in first select box, the second selected box is does not clear the old values, I mean the new values are adding to the old list, It adding not updating. How can I clear the old values of my second select list for on change of my first select menu ?
My code is as follows,
Jquery:
$("#select-choice").on('change', function(event) {
//$('#select-choice-location option[value!="Select Location"]').remove();
var catg = this.value;
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select Location from Locationlog WHERE Category = '"+catg+"';", [], function (tx, res) {
for (var i = 0; i < res.rows.length; i++) {
var opt = '<option value="';
opt += res.rows.item(i).Location;
opt += '">';
opt += res.rows.item(i).Location;
opt += '</option>';
$("#select-choice-location").append(opt);
}
$("#select-choice-location").listview('refresh');
});
});
});
HTML code:
<select name="select-choice" id="select-choice">
<option value="Select Category">Select Category</select>
</select>
<select name="select-choice-location" id="select-choice-location">
<option value="Select Location">Select Location</select>
</select>
You missed to clear the old option htmls.
Use empty() it will clear the old one
Try this
$("#select-choice-location").empty().append(opt)
OR
$("#select-choice").on('change', function(event) {
$("#select-choice-location").empty(); // Here you clear
var catg = this.value;
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select Location from Locationlog WHERE Category = '"+catg+"';", [], function (tx, res) {
var opt = '<option value="">Select</option>';
for (var i = 0; i < res.rows.length; i++) {
opt += '<option value="';
opt += res.rows.item(i).Location;
opt += '">';
opt += res.rows.item(i).Location;
opt += '</option>';
$("#select-choice-location").append(opt);
}
$("#select-choice-location").listview('refresh');
});
});
});
OR
$("#select-choice").on('change', function (event) {
var catg = this.value;
var db = window.sqlitePlugin.openDatabase({
name: "MYDB"
});
db.transaction(function (tx) {
tx.executeSql("select Location from Locationlog WHERE Category = '" + catg + "';", [], function (tx, res) {
var opt = '<option value="">Select</option>';
for (var i = 0; i < res.rows.length; i++) {
opt += '<option value="';
opt += res.rows.item(i).Location;
opt += '">';
opt += res.rows.item(i).Location;
opt += '</option>';
}
$("#select-choice-location").empty().append(opt);
$("#select-choice-location").listview('refresh');
});
});
});
Try like this it will work.
$("#select-choice").on('change', function (event) {
$("#select-choice-location").empty(); // clear
var catg = this.value;
var db = window.sqlitePlugin.openDatabase({
name: "MYDB"
});
db.transaction(function (tx) {
tx.executeSql("select Location from Locationlog WHERE Category = '" + catg + "';", [], function (tx, res) {
var opt = '<option value="">Select</option>';
for (var i = 0; i < res.rows.length; i++) {
opt += '<option value="';
opt += res.rows.item(i).Location;
opt += '">';
opt += res.rows.item(i).Location;
opt += '</option>';
$("#select-choice-location").append(opt);
}
$('select').selectmenu('refresh', true);
});
});
});
Refer here JQM docs
OR try this one and apply your custom functions.
var options = {
Select1: ["A", "B", "C"],
Select2: ["D", "E", "F"],
Select3: ["G", "G", "I"]
};
$(function () {
$('#firstSelect').change(function () {
var x = $('#firstSelect :selected').val();
$('#secondSelect').html("");
for (index in options[x]) {
$('#secondSelect').append('<option value="' + options[x][index] + '">' + options[x][index] + '</option>')
};
});
});
Refer this FIDDLE DEMO
Please use this code
$("#select-choice").on('change', function(event) {
//$('#select-choice-location option[value!="Select Location"]').remove();
var catg = this.value;
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select Location from Locationlog WHERE Category = '"+catg+"';", [], function (tx, res) {
for (var i = 0; i < res.rows.length; i++) {
var opt = '<option value="';
opt += res.rows.item(i).Location;
opt += '">';
opt += res.rows.item(i).Location;
opt += '</option>';
$("#select-choice-location").empty();
$("#select-choice-location").append(opt);
}
$("#select-choice-location").listview('refresh');
});
});
});

Categories

Resources