3

I've got 2 select elements in my code. One for US states (#us_state) and second for cities (#city_name). When I choose a "state" the second select element must contain only that cities which exists in selected state. I use ajax, I done the request and got the response. Response format is id:name {"26332":"Abbott Park","27350":"Addieville", ...}. Now I want to add the response to option elements and append it to select element with #city_name id. But I don't know how to achieve this result. <option value="key">value</option>

$('#us_state').bind('change', function() {
    var projectId = $("#inputtitle").val();     
    var stateId =  $(this).val(); 
    var arrayData = {"projectId": projectId, "stateId":stateId};
    $.ajax({
          type: "GET",
          url: "/bidboldly/projects/editproject/",        
          data: arrayData,
          success : function(response) {
             ............
             ..........                         
          },
          error: function(){
            alert("error");
          }
    })
});
emilan
  • 12,825
  • 11
  • 32
  • 37

2 Answers2

2

Iterate through each array data received from the response & get the city name say in var city. Then use jquery append to append the option values (also remember to clear the options outside the iterating loop using $('#city_name').html("");)

$('#city_name').append('<option value="'+city+'">'+city+'</option>');
gopi1410
  • 6,567
  • 9
  • 41
  • 75
  • And how to get city name and id ? My question is that. – emilan Apr 22 '12 at 08:29
  • 1
    [http://stackoverflow.com/questions/182410/how-to-json-decode-array-elements-in-javascript](http://stackoverflow.com/questions/182410/how-to-json-decode-array-elements-in-javascript) – gopi1410 Apr 22 '12 at 08:34
  • see the above post, there are many methods to decode json data, also you could proceed considering it as an array. Play with for(data in result), accessing it as objects etc etc, & you can successfully debug it within minutes. – gopi1410 Apr 22 '12 at 08:36
1

Is this what you're looking for?

data = eval('( '+response' )'); //Parse the JSON data
for (zip in data) { //Iterate through each item in data
    $('#city_name').append('<option value="'+zip+'">'+data[zip]+'</option>'); //Append option to select element
}
Theron Luhn
  • 3,974
  • 4
  • 37
  • 49