开发者

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

开发者 https://www.devze.com 2023-01-09 07:20 出处:网络
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 Y

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 th开发者_StackOverflowis.

Thank you.


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();
    }
});


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消