parsing - Chained State city dropdown list from JSON -
i trying populate chained state city select dropdowns. using external json file so, consists of state , corresponding city name, id , pincode. can gimme idea on how achieve this. need populate city , pincode value based on state selection. in advance...
json
{ "alaska" : [ {"id": "1", "name": "adak", "pincode": "xxx1"}, {"id": "2", "name": "akhiok", "pincode": "xxx2" }, {"id": "3", "name": "akiak", "pincode": "xxx3" }, ], "arizona" : [ {"id": "4", "name": "apache junction", "pincode": "xxx4"}, {"id": "5", "name": "avondale", "pincode": "xxx5"}, {"id": "6", "name": "benson", "pincode": "xxx6"}, ], "alabama" : [ {"id" : "5", "name": "abbeville", "pincode": "xxx7" }, {"id" : "7", "name": "adamsville", "pincode": "xxx8" }, {"id" : "8", "name": "akron", "pincode": "xxx9" }, ] }
final rendered html
<select id="state"> <option value="1">alaska</option> <option value="2">arizona</option> <option value="3">alabama</option> </select> <select id="city"> <option value="4">adak</option> <option value="5">akhiok</option> <option value="6">akiak</option> </select> <input id="pincode" type="text" />
i find question interesting , wrote corresponding solution can see live here.
here code:
jquery(document).ready(function () { var mydata; var oncitychange = function (e) { var citydata = $("option:selected", e.target).data('pincode'); $("#pincode").val(citydata.pincode); }; var onstatechange = function (e) { var state = $("option:selected", e.target).text(); if (state && mydata) { var statedata = mydata[state]; if (statedata && statedata.length > 0) { $("#city").empty(); $("#city").unbind('change'); (var = 0; < statedata.length; i++) { var citydata = statedata[i]; var option = $('<option value="' + citydata.id + '">' + citydata.name + '</option>') .data('pincode', citydata); $("#city").append(option); } $("#city").bind('change', oncitychange) .trigger('change'); } } }; $.ajax({ url: 'dependendselectsfromjson.json', datatype: 'json', success: function (data) { var stateoptions = "", stateid = 1; (var prop in data) { if (data.hasownproperty(prop)) { stateoptions += '<option value="' + stateid + '">' + prop + '</option>'; stateid++; } } mydata = data; $("#state").html(stateoptions) .bind('change', onstatechange) .trigger('change'); } }); });
to access pincode
of second (city) select box used jquery.data function find practical if 1 need associate additional information dom element. 1 save pincode
value in way, used function save full information city.
updated: forgot mention json data posted has errors. should remove commas before ']'. problem cut&paste of data text of question.
Comments
Post a Comment