Populate select elements dynamically from json data file using jquery - javascript

I'am trying to create search box for state districts and villages , but I'am enable to fetch data into combobox.
I have tried so many other way to get data into select boxes they doesn't work. Below is the code I've so far:
HTML:
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
JS:
<!-- language: lang-js -->
function loadlist(selobj, url) {
$(selobj).empty();
$(selobj).append('<option value="0">--Select Category--</option>')
$(selobj).append(
$.map(jsonList, function(el, i) {
return $('<option>').val(el.slno).text(el.state)
}));
}
loadlist($('select#state_id').get(0), jsonList);

You can do the following (Check the revision history for a shorter version which made use of underscorejs):
The comments should help you get an idea. check https://api.jquery.com/ for detailed information regarding the jQuery methods used.
$(function() {
insert($('#state_id'), plucker(records, 'state'));
//------------------------^ grabs unique states
//--^ populate state list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value),'district'));
//-^ insert plucked results to DOM
//------------------------^ plucks districts from filter results
//--------------------------------^ filters districts belonging to selected state
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value),'village'));
break;
}
}
});
function plucker(arr, prop) {
// grabs unique items from the required property such as state, district etc from the results
return $.map(arr, function(item) {
return item[prop]
}).filter(function(item, i, arr) {
return arr.indexOf(item) == i;
});
}
function filter(arr, key, value) {
// filters the records matching users selection
return $.grep(arr, function(item) {
return item[key] == value;
});
}
function insert(elm, arr) { // inserts the results into DOM
elm.find('option:gt(0)').remove();
$.each(arr, function(i,item) {
elm.append($('<option>', {
value: i,
text: item
}));
});
}
});
var records = [{
"slno": "1",
"state": "Maharashtra",
"constituency": "Parbhani",
"mp": "Shri Sanjay Haribhau Jadhav",
"district": "Parbhani",
"block": "Jintur",
"village": "Kehal",
"latitude": "77.7",
"longitude": "19.33"
}, {
"slno": "2",
"state": "Maharashtra",
"constituency": "Shirur",
"mp": "Shri Shivaji Adhalrao Patil",
"district": "Pune",
"block": "Shirur",
"village": "Karandi",
"latitude": "77.7",
"longitude": "19.33"
}, {
"slno": "3",
"state": "Maharashtra",
"constituency": "Amravati",
"mp": "Shri Anandrao Vithoba Adsul",
"district": "Amravati",
"block": "Amravati",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
}]
$(function() {
insert($('#state_id'), plucker(records, 'state'));
//------^ populate states list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value), 'district'));
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value), 'village'));
break;
}
}
});
function plucker(arr, prop) {
// grabs unique items from the required property such as state, district etc from the results
return $.map(arr, function(item) {
return item[prop]
}).filter(function(item, i, arr) {
return arr.indexOf(item) == i;
});
}
function filter(arr, key, value) {
// filters the records matching users selection
return $.grep(arr, function(item, i) {
return item[key] === value;
});
}
function insert(elm, arr) {
// inserts the results into DOM
elm.find('option:gt(0)').remove();
$.each(arr, function(i, item) {
elm.append($('<option>', {
value: i,
text: item
}));
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>

In your above code you have made the following mistake,
1.Extra close bracket
$.map(jsonList, function (el, i) {
return $('<option>').val(el.slno).text(el.state)
}));
Update it as
$.map(jsonList, function (el, i) {
return $('<option>').val(el.slno).text(el.state)
});
The looping of json object
$.map(jsonList.listval, function (el, i) {
$('#state_id').append('<option value="'+el.slno+'" attState="'+el.state+'">'+el.state+'</option>');
});
To avoid multiple times the same state repetition, before inserting the option you need to check if the entry is already exist in option if not exist then add it to the select, for this I have introduced a new option attribute "attState". Please look in to the code you will understand what I have done..
$.map(jsonList.listval, function (el, i) {
if ($("#yourSelect option[attState='" + el.state + "']").length == 0) {
$('#yourSelect').append('<option value="' + el.slno + '" attState="' + el.state + '">' + el.state + '</option>');
}
});
For reference refer

Try:
function createOptiolist(list, name) {
var state = list.map(function(obj) {
return obj[name];
});
return state = state.filter(function(v, i) {
return state.indexOf(v) == i;
});
}
var state = createOptiolist(jsonList.listval, "state");
$.each(state, function(i, el) {
$('#state_id').append('<option value="' + el + '">' + el + '</option>');
});
$('#state_id').on('change', function() {
var state = $(this).find('option:selected').val();
$('#district_id').empty();
$.each(jsonList.listval, function(i, el) {
if (el.state == state) {
$('#district_id').append('<option value="' + el.district + '">' + el.district + '</option>');
}
})
});
$('#district_id').on('change', function() {
var district = $(this).find('option:selected').val();
$('#village_id').empty();
$.each(jsonList.listval, function(i, el) {
if (el.district == district) {
$('#village_id').append('<option value="' + el.slno + '">' + el.village + '</option>');
}
})
});
DEMO
DEMO with ajax

Try this plz
HTML
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
JQUERY
$(document).ready(function(){
// JSON list
var jsonList = {"listval" : [
{
"slno": "1",
"state": "Maharashtra",
"constituency": "Parbhani",
"mp": "Shri Sanjay Haribhau Jadhav",
"district": "Parbhani",
"block": "Jintur",
"village": "Kehal",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "2",
"state": "Maharashtra",
"constituency": "Shirur",
"mp": "Shri Shivaji Adhalrao Patil",
"district": "Pune",
"block": "Shirur",
"village": "Karandi",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "3",
"state": "TEXAS",
"constituency": "XYZ",
"mp": "Shri ABC",
"district": "dist1",
"block": "block1",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "4",
"state": "Maharashtra",
"constituency": "Amravati",
"mp": "Shri Anandrao Vithoba Adsul",
"district": "Amravati",
"block": "Amravati",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
}]}
// JSON LIST
function loadlist(selobj, url) {
var categories = [];
$(selobj).empty();
$(selobj).append('<option value="0">--Select Category--</option>')
$(selobj).append(
$.map(jsonList.listval, function (el, i) {
if ($.inArray(el.state, categories)==-1) {
categories.push(el.state);
return $('<option>').val(el.slno).text(el.state);
console.log($(el.state));}
}));
}
loadlist($('#state_id').get(0), jsonList);
});

Related

3 level multiple cascanding dropdown using Array

I am trying to create a 3 level dropdown with data, but the second and third dropdowns still show the data as a whole. How to have the second and third dropdown filter data based on related data?
var json = [{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES"
},
{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES 2"
},
{
"country": "USA",
"state": "New York",
"city": "New York",
},
{
"country": "USA",
"state": "New York",
"city": "New York 2",
},
{
"country": "CANADA",
"state": "British Columbia",
"city": "Vancovour",
}
];
for (i = 0; i < json.length; i++) {
$("#country").append("<option value=" + json[i]["country"] + ">" + json[i]["country"] + "</option>");
$("#state").append("<option value=" + json[i]["country"] + ">" + json[i]["state"] + "</option>");
$("#city").append("<option value=" + json[i]["country"] + ">" + json[i]["city"] + "</option>");
}
$("#state").change(function() {
$("#country")[0].selectedIndex = $(this)[0].selectedIndex
$("##city")[0].selectedIndex = $(this)[0].selectedIndex
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="myform" id="myForm">
<select name="opttwo" id="country" size="1">
<option value="" selected="selected">Please select state </option>
</select>
<br>
<br>
<select name="optone" id="state" size="1">
<option value="" selected="selected">Please Select country first</option>
</select>
<br>
<br>
<select name="optthree" id="city" size="1">
<option value="" selected="selected">Please select country first</option>
</select>
</form>
I have tried to make it like this. what should I add?
var json = [{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES"
},
{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES 2"
},
{
"country": "USA",
"state": "New York",
"city": "New York",
},
{
"country": "USA",
"state": "New York",
"city": "New York 2",
},
{
"country": "CANADA",
"state": "British Columbia",
"city": "Vancovour",
}
];
function addElementsFor(c, v, index) {
var tracker = [];
for (var i = 0, o; o = json[i]; i++) {
if (!!v && !!index && o[v] !== json[index][v]) {
continue;
}
if (tracker.indexOf(o[c.id]) !== -1) {
continue;
}
tracker.push(o[c.id]);
var option = document.createElement('option');
option.value = i;
option.innerText = o[c.id];
c.appendChild(option);
}
return c
}
function populateSubCategory(c, v, index) {
var state = document.getElementById(c);
state.disabled = false;
while (state.firstChild) state.firstChild.remove();
var option = document.createElement('option');
option.value = -1;
option.innerText = '----';
state.appendChild(option);
if (index * 1 < 0) return;
return addElementsFor(state, v, index);
}
window.addEventListener('load', function() {
addElementsFor(document.getElementById('country')).addEventListener('change', function(ev) {
populateSubCategory('state', ev.target.id, ev.target.value).addEventListener('change', function(ev) {
populateSubCategory('city', ev.target.id, ev.target.value).addEventListener('change', function(ev) {
if (ev.target.value * 1 < 0) {
return;
}
var country = document.getElementById('country');
var state = document.getElementById('state');
var city = ev.target;
if (json.hasOwnProperty(country.value) && json.hasOwnProperty(state.value) && json.hasOwnProperty(city.value)) {
console.log('country: %s state: %s city: %s', json[country.value]['country'], json[state.value]['state'], json[city.value]['city']);
}
})
})
})
});
<form name="myform" id="myForm">
<select name="opttwo" id="country" size="1">
<option value="-1" selected="selected">Please select state </option>
</select>
<br>
<br>
<select name="optone" id="state" size="1">
<option value="-1" selected="selected">Please Select country first</option>
</select>
<br>
<br>
<select name="optthree" id="city" size="1">
<option value="-1" selected="selected">Please select country first</option>
</select>
</form>
You need to check if there is already a select element with the same content before adding it again or you will end up with duplicates.
Check this thread: https://stackoverflow.com/a/9791018/5211055

Dependent Dropdown list in Javascript, jQuery, Json & Ajax

How can I make it so when I select an option it will only populate that one area?
I only want the specific places in that area.
example picture.]
Example of the output (1)
Example of the output (2)
this is the json code that I want to have a function and connect the two or more files.
json file 1
{
"code": "010000000",
"name": "Ilocos Region",
"altName": "Region I"
}
json file 2
{
"code": "012800000",
"name": "Ilocos Norte",
"altName": null,
"region": "010000000"
},
{
"code": "012900000",
"name": "Ilocos Sur",
"altName": null,
"region": "010000000"
},
{
"code": "013300000",
"name": "La Union",
"altName": null,
"region": "010000000"
},
{
"code": "015500000",
"name": "Pangasinan",
"altName": null,
"region": "010000000"
}
here is the code
html part
<div class="container form-group" style="width:600px; margin-top: 10vh">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region" class="form-control input-sm" required>
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province" class="form-control input-sm" required>
<option value="">Select Province</option>
</select>
</div>
</form>
</div>
<script>
$(function(){
let regionOption;
let provinceOption;
//FOR REGION
$.getJSON('regions.json', function(result){
regionOption += `<option value="">Select Region</option>`;
$.each(result, function(i, region){
regionOption += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regionOption);
});
//FOR PROVINCE
$('#region').change(function(){
$.getJSON('provinces.json', function(result){
provinceOption += `<option value="">Select Province</option>`;
$.each(result, function(region, province){
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
});
});
});
</script>
my failed attempt is this part :
$('#region').change(function(){
if($(this).val() === $(this).val()){
$.getJSON('provinces.json', function(result){
provinceOption += `<option value="">Select Province</option>`;
$.each(result, function(region, province){
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
});
}
});
You can use .filter() to filter your json return inside ajax then inside this compare value of select-box with all values of region if they matches get that data . Finally loop through filter datas and show them inside your select-box.
Demo Code :
//just for demo :)
var result = [{
"code": "010000000",
"name": "Ilocos Region",
"altName": "Region I"
}, {
"code": "010000002",
"name": "Ilocos Region2",
"altName": "Region 2"
}]
var json2 = [
{
"code": "012800000",
"name": "Ilocos Norte",
"altName": null,
"region": "010000000"
},
{
"code": "012900000",
"name": "Ilocos Sur",
"altName": null,
"region": "010000000"
},
{
"code": "013300000",
"name": "La Union",
"altName": null,
"region": "010000002"
},
{
"code": "015500000",
"name": "Pangasinan",
"altName": null,
"region": "010000002"
}
]
$(function() {
let regionOption;
let provinceOption;
//FOR REGION
/* $.getJSON('regions.json', function(result) {*/
regionOption += `<option value="">Select Region</option>`;
$.each(result, function(i, region) {
regionOption += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regionOption);
/* });*/
$('#region').change(function() {
var values = $(this).val()
var provinceOption = ""
/*$.getJSON('provinces.json', function(json2) {*/
//filter your json return..
var items = $(json2)
.filter(function(i, n) {
return n.region === values; //get value where region is same
});
provinceOption += `<option value="">Select Province</option>`;
//loop through dates
$.each(items, function(region, province) {
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
/* });*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container form-group" style="width:600px; margin-top: 10vh">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region" class="form-control input-sm" required>
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province" class="form-control input-sm" required>
<option value="">Select Province</option>
</select>
</div>
</form>
</div>

How can I fill a probably infinite amount of dropdowns iterating through objects from a JSON file?

So, I'm trying to fill three separate dropdown menus (could end up being more) with objects pulled from different JSON files depending on the selection from each dropdown. So first selection fills the second one, and so on.
These are the dropdown menus:
<form>
<div>
<select id="level1">
<option selected value="base">Please select one</option>
<option value="first-option">First one</option>
<option value="second-option">Second one</option>
</select>
</div>
<div>
<select id="level2" class="form-control">
<option selected value="base">Please select one</option>
</select>
</div>
<div>
<select id="level3" class="form-control">
<option selected value="base">Please select one</option>
</select>
</div>
<div id="submit">
<button type="submit">Go</button>
</div>
</form>
This is a sample JSON file:
{
"first_option": {
"me": "first_option",
"COD_REF": "MX09017CL01AP",
"TITLE": "First Option",
"children": {
"child01": {
"me": "child01",
"COD_REF": "001",
"TITLE": "Child 1",
"children": {
"grandchild01": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
},
"grandchild02": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
}
}
}
},
"child02": {
"me": "child02",
"COD_REF": "002",
"TITLE": "Child 2",
"children": {
"grandchild01": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
},
"grandchild02": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
}
}
},
}
}
The solution I came up with works just fine. The thing is I could probably do with some iteration, I just don't know how to do it. Here's an abridged version of what I have:
var vals = [];
var $level1 = $("#level1");
var $level2 = $("#level2");
var $level3 = $("#level3");
function generateTable(info) {
$(".COD_REF").innerHTML(info.COD_REF);
$(".TITLE").innerHTML(info.TITLE);
};
function generateTable2(info) {
$(".COD_REF").innerHTML(info.COD_REF);
$(".TITLE").innerHTML(info.TITLE);
}
function generateTable3(info) {
$(".COD_REF").innerHTML(info.COD_REF);
$(".TITLE").innerHTML(info.TITLE);
}
//first dropdown
$("#level1").change(function () {
var $dropdown = $(this);
var key = $dropdown.val();
function generateDropdown(vals) {
$level2.append("<option selected value=\"base\">Please select one</option>");
$.each(vals, function (index, value) {
$level2.append("<option value=\"" + value.me + "\">" + value.TITLE + "</option>");
});
};
switch (key) {
case 'first_option':
$.getJSON("recursos/json/ajsonfile.json", function (data) {
$level2.empty();
vals = data.first_option.children;
generateDropdown(vals)
$("#first-table").removeClass("d-none");
$("#first-table").addClass("d-block");
info = data.first_option;
$(".first-title").innerHTML(info.TITLE);
generateTable(info);
});
break
case 'second_option':
$.getJSON("recursos/json/anotherjsonfile.json", function (data) {
$level2.empty();
vals = data.second_option.children;
generateDropdown(vals)
$("#first-table").removeClass("d-none");
$("#first-table").addClass("d-block");
info = data.second_option;
$(".first-title").innerHTML(info.TITLE);
generateTable(info);
});
break
case 'base':
$level2.empty();
vals = ['Please select one'];
$level2.append("<option>" + vals + "</option>");
$("#first-table").removeClass("d-block");
$("#first-table").addClass("d-none");
console.log(vals);
break
}
});
//second dropdown
$("#level2").change(function () {
var $dropdown = $(this);
var key = $dropdown.val();
function generateDropdown(vals) {
$level3.append("<option selected value=\"base\">Please select one</option>");
$.each(vals, function (index, value) {
$level3.append("<option value=\"" + value.yo + "\">" + value.TITLE + "</option>");
});
};
switch (key) {
case 'first-child':
$.getJSON("recursos/json/ajsonfile.json", function (data) {
$level3.empty();
vals = data.first_option.children.child01.children;
generateDropdown(vals)
$("#second-table").removeClass("d-none");
$("#second-table").addClass("d-block");
info = data.first_option.children.child01;
$(".second-title").innerHTML(info.TITLE);
generateTable2(info);
});
break
//second, third, fourth child options etc.
case 'base':
$level3.empty();
vals = ['Please select one'];
$level3.append("<option>" + vals + "</option>");
$("#cedula2").removeClass("d-block");
$("#cedula2").addClass("d-none");
console.log(vals);
break
}
});
//third dropdown
$("#level3").change(function () {
// I think you get the gist
});
Is it possible to do some iteration so I can fill all the dropdowns in just one loop?

Fill data in options in select box using jquery

I have an json array with some data i want to fill all its value in select box option value ...
Array like
[
{
"CityId": "42231",
"CountryID": "1",
"RegionID": "833",
"City": "Herat",
"Latitude": "34.333",
"Longitude": "62.2",
"TimeZone": "+04:30",
"DmaId": "0",
"Code": "HERA"
},
{
"CityId": "5976",
"CountryID": "1",
"RegionID": "835",
"City": "Kabul",
"Latitude": "34.517",
"Longitude": "69.183",
"TimeZone": "+04:50",
"DmaId": "0",
"Code": "KABU"
},
{
"CityId": "42230",
"CountryID": "1",
"RegionID": "852",
"City": "Mazar-e Sharif",
"Latitude": "36.7",
"Longitude": "67.1",
"TimeZone": "+4:30",
"DmaId": "0",
"Code": "MSHA"
}
]
and i want to fill this value in select box using jquery, how can i do this...
i have tried
$.each(json, function(i, value) {
$('#cityselect').append($('<option>').text(value.CityId).attr('value.city', value.City));
});
can anyone help me for this
var data = [{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}];
Now for populating the options:
var $select = $('#cityselect');
$.each(data, function(i , value) {
var option = $('<option value="'+ value.CityId+'">'+ value.City +'</option>');
$select.append(option);
});
Even more better in terms of performance:
var data = [{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}];
var $select = $('#cityselect');
options = [];
$.each(data, function(i , value) {
options.push('<option value="'+ value.CityId+'">'+ value.City +'</option>');
});
$select.html(options.join(""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cityselect"></select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<select id="cityselect"></select>
</body>
<script>
$(document).ready(function () {
var listVal=[{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}] ;
$.each(listVal, function(i, value) {
$('#cityselect').append('<option value="'+ value.CityId+'">'+ value.City +'</option>');
});
});
</script>
</html>
You can make use of .val(id) to set the id and .text(name) to set the name of option.
$('#cityselect').append($('<option />').val(value.CityId).text(value.City));
var json = [{"CityId":"42231","CountryID":"1","RegionID":"833","City":"Herat","Latitude":"34.333","Longitude":"62.2","TimeZone":"+04:30","DmaId":"0","Code":"HERA"},{"CityId":"5976","CountryID":"1","RegionID":"835","City":"Kabul","Latitude":"34.517","Longitude":"69.183","TimeZone":"+04:50","DmaId":"0","Code":"KABU"},{"CityId":"42230","CountryID":"1","RegionID":"852","City":"Mazar-e Sharif","Latitude":"36.7","Longitude":"67.1","TimeZone":"+4:30","DmaId":"0","Code":"MSHA"}];
$.each(json, function(i, value) {
$('#cityselect').append($('<option />').val(value.CityId).text(value.City));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='cityselect'> </select>

Combo Select using json

The country and state will be sent as json
{
"data": [
{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"
]
},
{
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"
]
}
]
}
There will be two select tags (country and state). How do I populate the states based on the country selected?
I am looking for a solution similar to http://www.datatables.net/examples/api/row_details.html where the row.data() returns the data set of a particular row.
Here's a very simple pure JavaScript way to populate two select boxes via JSON. In this example, State is dependent upon which Country is selected.
Example: http://jsfiddle.net/wasfd592/
HTML:
<select id="country">
<option>Country</option>
</select>
<select id="state">
<option>State</option>
</select>
JSON Object (assigned to variable d):
var d = {
"data": [
{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"
]
},
{
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"
]
}
]
}
JavaScript:
// First - populate the Country select box from the JSON
for (var i in d.data) {
var elem = document.createElement("option");
elem.value = d.data[i].country;
elem.innerHTML = d.data[i].country;
document.getElementById("country").appendChild(elem);
}
// Next - add an event handler that will trigger when Country is changed and populate the State box
document.getElementById("country").addEventListener("change", function () {
document.getElementById("state").innerHTML = "";
var country = document.getElementById("country").options[document.getElementById("country").selectedIndex].value;
if (country === "Country") {
var elem = document.createElement("option");
elem.value = "State";
elem.innerHTML = "State";
document.getElementById("state").appendChild(elem);
}
for (var i in d.data) {
if (d.data[i].country === country) {
for (var a = 0; a < d.data[i].states.length; a++) {
var elem = document.createElement("option");
elem.value = d.data[i].states[a];
elem.innerHTML = d.data[i].states[a];
document.getElementById("state").appendChild(elem);
}
}
}
});
Try this out:- http://jsfiddle.net/ox4ykqoL/
HTML:-
<select id="country"></select>
<select id="states"></select>
JS:-
jQuery(function ($) {
var input = {
"data": [{
"country": "USA",
"states": [
"Alabama",
"Alaska",
"Arizona"]
}, {
"country": "India",
"states": [
"TN",
"AP",
"Mumbai"]
}]
};
$.each(input.data, function (index, d) {
$("#country").append("<option value=\"" + d.country + "\">" + d.country + "</option>");
});
$("#country").on("change", function () {
var selectedCountry = $("#country").val();
var t = $.map(input.data, function (obj) {
if (obj.country === selectedCountry) return obj;
});
if (t.length != 0) {
$('#states').empty();
debugger;
$.each(t[0].states, function (index, d) {
$("#states").append("<option value=\"" + d + "\">" + d + "</option>");
});
}
});
$("#country").change();
});

Categories

Resources