user569322
user569322

Reputation:

JQuery, change <select> options?

On my website, I want to make it so that a user can choose a State and City to go to. If the user selects a state, how would I make it so that the city select box would change all of the cities in the <option> tags?

For example:

Virginia is chosen, so I'd want to change the cites to Richmond, Arlington, Fredricksburg, etc.

Upvotes: 3

Views: 4701

Answers (1)

Joseph at SwiftOtter
Joseph at SwiftOtter

Reputation: 4321

There are a couple of ways to do this, depending upon the architecture of your website. My favorite would be to fire off a $.ajax, pull the result down, and load it into the next select. That is the most extensible, IMHO, but not the fastest for the end user. If it isn't a huge list (meaning, download speed), you could load the information into arrays or classes and use that to populate the information.

I would probably do something like this:

$("#cities option").remove();
$(citylist[$("#state").val()]).each(function() {
    $("#cities").append('<option value="' + this + '">' + this + '</option>');
});

Please note, I haven't tested this, so it may not work, but I think it should send you in the write direction.

JMax

Upvotes: 3

Related Questions