I have 2 select menus with matching options e.g
<select id="select-one">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="select-two">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
What I need to do inside the change function is if an option is selected from either menu, hide/remove the matching option from the other list. I need to show it again when a different option is selected.
I hope that’s enough info but please ask if you need any more.
EDIT
Sorry I missed it out but I am using the chosen plugin
The first thing I’d personally do is add a
data-*attribute to each of your selects, containing the ID of the other select. That allows you to make your code more generic, rather than having to mostly duplicate it with switched IDs:Then the jQuery code:
That adds a
changeevent handler to the two selects. The first thing it does is store a copy ofthis(the<select>that was changed) into another variable, so it can refer to it inside the function passed to.filter().Then it gets a reference to the other
<select>element, using thedata-selectattribute of the element.Now it selects all option elements inside that, and shows them, then filters that list down to just the one with the matching value, and hides that.
UPDATE:
If you’re calling the chosen plugin on the
<select>elements individually, you may want to move the anonymous function to a named function, like so:Then pass a reference to that function when assigning your
changeevent handlers individually: