user1301411
user1301411

Reputation: 224

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

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>

Upvotes: 3

Views: 3961

Answers (3)

Josh Johnson
Josh Johnson

Reputation: 11107

As of HTML 5 we have the hidden attribute. I had to do a similar thing recently, though with React so I'll leave the exact plumbing up to you, but you can set your optgroup to hidden a la

<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>                                <!-- hidden-->
    <option value="Ontario">Ontario</option>                 <!-- hidden-->
    <option value="Quebec">Quebec</option>                   <!-- hidden-->
  </optgroup>
</select>

Upvotes: 0

VisioN
VisioN

Reputation: 145408

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/

Upvotes: 5

Claudio Redi
Claudio Redi

Reputation: 68400

I don't think you can do that in a cross browser manner. I'd say the best option is to store all options and recreate the select with filtered options

Upvotes: 1

Related Questions