TRAVA
TRAVA

Reputation: 211

Hide/Show <select> depending on the other <select>

I have two <select> elements. The first one contains countries (e.g. USA, Canada, England, Russia, Poland...) and the second one is hidden, containing cities from only USA and Canada (e.g. New York, Los Angeles, Chicago... OR Ottawa, Vancouver, Surrey...)

If the user selects Canada or USA from the first <select>, the second should show and allow him to select his city.

Is it possible to do? I visited so many websites with Ajax and JQuery Validation forms and didn't find some similar source to make this.

Thank you.

Upvotes: 1

Views: 819

Answers (2)

Anurag
Anurag

Reputation: 141869

Listen to the change event for the select list. In the change event, if the selected value is "USA" or "Canada" then show the other select list, otherwise hide it.

See an example.

Assuming the select structure looks like this:

<select id="countries">
    <option val="USA">USA</option>
    <option val="Canada">Canada</option>
    <option val="Australia">Australia</option>
    ...
</select>

<select id="cities">
    <option val="Vancouver">Vancouver</option>
    <option val="New York">New York</option>
    ...
</select>

Listen to the change event on the countries array.

$("#countries").change(function() {
    // find the selected country
    var selectedCountry = $(this).val();
    // if US or Canada
    if(selectedCountry == "USA" || selectedCountry == "Canada") {
        // show the cities list
        $("#cities").show();
    }
    // otherwise hide it
    else {
        $("#cities").hide();
    }
});

Upvotes: 1

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

It is really simple.
First of all prepare change event handler http://api.jquery.com/change/
Second, check value of your select val : http://api.jquery.com/val/
Third, display or hide your second select. http://api.jquery.com/hide/ or http://api.jquery.com/show/

Upvotes: 1

Related Questions