Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set option to select box

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");
          }
    })
});
like image 513
emilan Avatar asked Dec 04 '25 02:12

emilan


2 Answers

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>');
like image 183
gopi1410 Avatar answered Dec 06 '25 15:12

gopi1410


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
}
like image 37
Theron Luhn Avatar answered Dec 06 '25 16:12

Theron Luhn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!