I have following simple Html code with 2 SELECT forms with identical options values:
<select id="first">
<option value="none">None</option>
<option value="one">Toyota</option>
<option value="two">Nissan</option>
</select>
<select id="second">
<option value="none">None</option>
<option value="one">Toyota</option>
<option value="two">Nissan</option>
</select>
I am writing a jquery script that should do following: if in the #first select I choose any value except "none", f.e. Toyota, it will automatically disappear from the #second select:
<select id="second">
<option value="none">None</option>
<option value="two">Nissan</option>
</select>
further, if I choose Nissan in the #second select(assuming #first still have Toyota selected), it should automatically disappear from the #first select:
<select id="first">
<option selected="selected" value="one">Toyota</option>
<option value="none">None</option>
</select>
At the end, when I reset selector to "None" in any select form, it should recreate that option in another select on the same position.
How is that better to achieve? is it better to use .remove()/.append() actions or .hide()/.unhide()? So far I create following snippet:
$(document).on('change','select', function() {
var sel = $(this).attr('id');
var val = $(this).val();
if ( sel === "first" && val != "none") {
$("#second option[value="+val+"]").remove();
} else if ( sel === "second" && val != "none") {
$("#first option[value="+val+"]").remove();
}
this just removes selected option from another select, but how to correctly re-create option on the same position after changing select to "None"?
UPDATE: .hide() function doesn't work in some browsers, I need to use .remove()/.append(), but the problem is that how to append to the position that it was before?