D Durham D Durham - 5 months ago 24
HTML Question

JS keep to selects in sync (no jquery)

I have two SELECT elements on a page and what I need to do is if the first one is changed, have the second contain all the OPTIONS from the first except the one that is currently selected in the first.

They start off with identical options and I can disable the second until the first is selected if needed. So, if I have:

...
<select id="selectOne" onchange="someFuntion()">
<option value="1">One</>
<option value="2">Two</>
<option value="3">Three</>
</select>

<select id="selectOne" onchange="someFuntion()">
<option value="1">One</>
<option value="2">Two</>
<option value="3">Three</>
</select>
...


...and Two is selected in the first, then it should be removed from the second. Then if Three is selected in the first, the second should have everything in listed in the first (including Two again) except Three. The first ones options never change and the second should always have everything in the first except the currently selected option. Any ideas on how best to accomplish something like this?

I cannot bring JQuery into the mix for this, so please no Jquery specific answers. Beyond that open to pretty much anything. I can get the initial value selected in the first removed from the second, but am not sure how to handle changes from there.

TIA!

Answer

If disabling the options in selectTwo is fine, you might do something like this. If not, you might "hide" the matching option with a display:none class and use classList.add and classList.remove to hide and show rather than disable and enable.

Both the hide and disable methods here result in the possibility that the item to remove is the once currently selected in selectTwo. Neither strategy is great in that situation. If you must avoid it, you might either set the value of selectTwo to a "good" one or alternatively, delete the children of selectTwo and clone the non-selected children of selectOne and add those to selectTwo.

If you want an example of the remove/clone strategy let me know and I will post that.

function selectClick(event) {
  var that = document.querySelector("#selectTwo");
  var thatOptions = that.querySelectorAll("option");

  for (var i = 0; i < thatOptions.length; i++) {
    thatOptions[i].disabled = (thatOptions[i].value === this.value);
  }
}

document.querySelector("#selectOne").addEventListener("change", selectClick);
<select id="selectOne">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

<select id="selectTwo">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>