Joel Joel - 3 months ago 5
Javascript Question

Update Select Menu based off another Selection

I have a list of states (USA) that includes Canadian provinces,

<optgroup label="United States">
<option value="AL">Alabama (AL)</option><option value="AK">Alaska (AK)</option><option value="AE">APO state (AE)</option><option value="AO">APO state (AO)</option><option value="AP">APO state (AP)</option><option value="AZ">Arizona (AZ)</option>
<optgroup label="Canada">
<option value="AB">Alberta (AB)</option><option value="BC">British Columbia (BC)</option><option value="MB">Manitoba (MB)</option><option value="NB">New Brunswick (NB)</option><option value="NL">Newfoundland and Labrador (NL)</option></optgroup>

Then I have another select menu that includes 2 options, USA & Canada. (USA is default selected)

I want that if Canadian province is selected, disable USA as country in second select menu. and if Canada is selected in second select menu, remove USA states from first select menu.

I only found ways to populate the second select menu after choosing the first (like this, but what I try is to show all by default, and update after selecting either one.


You can do something like this:

$("#filter").on("change", function() {
    $states = $("#states");
    $states.find("optgroup[label='" + this.value + "']").show().children().show();
    $states.find("optgroup[label='" + this.value + "'] option").eq(0).prop("selected", true);

See this working DEMO