I have multiple selects:
<select id="one"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> <select id="two"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select>
What I want is to select “one” from the first select, then have that option be removed from the second one. Then if you select “two” from the second one, I want that one removed from the first one.
Here’s the JS I have currently:
$(function () { var $one = $("#one"); var $two = $("#two"); var selectOptions = []; $("select").each(function (index) { selectOptions[index] = []; for (var i = 0; i < this.options.length; i++) { selectOptions[index][i] = this.options[i]; } }); $one.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[1].length; i++) { var exists = false; for (var x = 0; x < $two[0].options.length; x++) { if ($two[0].options[x].value == selectOptions[1][i].value) exists = true; } if (!exists) $two.append(selectOptions[1][i]); } $("option[value='" + selectedValue + "']", $two).remove(); }); $two.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[0].length; i++) { var exists = false; for (var x = 0; x < $one[0].options.length; x++) { if ($one[0].options[x].value == selectOptions[0][i].value) exists = true; } if (!exists) $one.append(selectOptions[0][i]); } $("option[value='" + selectedValue + "']", $one).remove(); }); });
But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled
attribute on the option I want to remove, but that doesn’t work with IE6.
Answer
I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.