0

Possible Duplicate:
Use jquery to change second select list based on first select list option

I've got two select elements in my code. One for 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.

Community
  • 1
  • 1
Prinston J
  • 105
  • 1
  • 16
  • 1
    Do you have some sort of data source to fill both selects? Also, as always, your current code would help...either posted here or through a fiddle – gonzofish Oct 16 '12 at 10:39

2 Answers2

2

One possible solution:

var data = {
    "State 1": ["City 1", "City 2"],
    "State 2": ["City 3", "City 4"],
    "State 3": ["City 5", "City 6", "City 7"]
};

var $states = $("#us_state").on("change", function() {
    var $cities = $.map(data[this.value], function(city) {
        return $("<option />").text(city);
    });
    $("#city_name").empty().append($cities);
});

for (var state in data) {
    $("<option />").text(state).appendTo($states);
}​

DEMO: http://jsfiddle.net/8hbcP/

VisioN
  • 143,310
  • 32
  • 282
  • 281
0

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>');
rahul
  • 7,573
  • 7
  • 39
  • 53