开发者

Chained State city dropdown list from JSON

I am trying to populate a chained State City select dropdowns. I am using an external json file to do so, which consists of State and their corresponding city name, id and pincode. Can somebody gimme some idea on how to achieve this. I need to populate the city and pincode value based on the state selection. Thanks 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>
      </s开发者_JAVA百科elect>

      <input id="pincode" type="text" />


I find your question interesting and wrote the corresponding solution which you can see live here.

Here is the 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');
                for (var i = 0; i < 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;
            for (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 get access about the pincode of the second (city) select box I used jQuery.data function which I find very practical if one need to associate some additional information with an DOM element. One could save only pincode value in the way, but I used the function to save full information about the city.

UPDATED: I forgot to mention that the JSON data which you posted has errors. You should remove commas before ']'. Probably it is just a problem with cut&paste of the data to the text of the question.


there are many ways.

global Varible option.

var json_object = {
"Alaska" : {}

}; //and the rest of other text too lazy to type :)

$('#state').change(function(){
  var state =  $(this).val();
  cities = json_object[state];
  $('#city').html('');//remove the prev elements
  for(item in cities){//same as foreach in php
     $('<option value=""></option>').appendTo($('#city'));
  }
});

i must admit is not complete but giving you the rough idea.

Other wise use ajax like so

$('#state').change(function(){
    var url = 'ajax.php';//should return json with a list of cities only
    var state = $('#state').val();
    var data = {'state':state};
    $.ajax({
        url:url,
        data:data,
        dataType:'json',
        success: function(items){
            //do something with it
        }
    })
});

The only thing you need to know is that both have their advantages and disadvantages.

first option : can only fire one request but loads sh*t loads of data that are not needed. second option: makes more request but less data

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜