Hide select's optgroups and their contents except the one selected

html, javascript, jquery, jquery-events

Solution

This seems to be working fine for me:

​$("select[name='country']:eq(0)"​).on("change", function() {
    $("select[name='country']:eq(1)")
        .find("optgroup,option")
        .hide()
        .filter("[label='" + this.value + "'],[label='" + this.value + "'] > *")
        .show();
});​​​​​​​​

DEMO: http://jsfiddle.net/MVkXg/

Problem

I want to create a select tag for countries that when we select the country it hides all optgroups and their contents of a select tag for states except the optgroup and its content which has the same label as the selected country option, example ``` <select name="country"> <option value="United States">United States</option> <!-- if I select US --> <option value="Canada">Canada</option> <option value="Mexico">Mexico</option> </select> <select name="country"> <optgroup label="United States"> <option value="California">California</option> <!-- Only these states --> <option value="New York">New York</option> <!-- are displayed --> </optgroup> <optgroup label="Canada"> <!-- hidden--> <option value="Ontario">Ontario</option> <!-- hidden--> <option value="Quebec">Quebec</option> <!-- hidden--> </optgroup> <optgroup label="Mexico"> <!-- hidden--> <option value="Baja California">Baja California</option> <!-- hidden--> <option value="Mexico Estado">Mexico Estado</option> <!-- hidden--> </optgroup> </select> ```

Original source