Reputation: 13075
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");
}
})
});
Upvotes: 3
Views: 497
Reputation: 6625
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>');
Upvotes: 2
Reputation: 4082
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
}
Upvotes: 1