Mazurky
Mazurky

Reputation: 43

html select option javascript

I have this table and these options in it. I want to do that when I select Binary in the first select list, it will not be automatically selected in the second select list. Friend told me that it can be done in JavaScript but he and I don't know how.

To better understand: if I select an option with value 2 in the first selector, it will not be possible to select it in the second select

so if someone could help me, answer please

<tr>
  <td class="center"> 
    <select id="notationoption" name="notation_from">
      <option value="2">Binary</option>
      <option value="3">Ternary</option>
      <option value="4">Quaternary</option>
    </select>
  </td> 
</tr>
<tr>
  <td class="center"> 
    <select id="notationoption" name="notation_to">
    <option value="2">Binary</option>
    <option value="3">Ternary</option>
    <option value="4">Quaternary</option> 
    </select>
  </td> 
</tr> 

Upvotes: 2

Views: 255

Answers (1)

Unmitigated
Unmitigated

Reputation: 89139

You can use the change event on the first select to disable the option with the same value in the second select. Also, you cannot have two elements with the same id, so you will need to give your second select a different id.

const select1 = document.getElementById("notationoption1");
const select2 = document.getElementById("notationoption2");
select1.addEventListener("change", e=>{
  const disabled = select2.querySelector("option[disabled]");
  if(disabled) disabled.disabled = false;
  select2.querySelector("option[value='"+ select1.value + "']").disabled = true;
});
<tr>
  <td class="center"> 
    <select id="notationoption1" name="notation_from">
      <option value="2">Binary</option>
      <option value="3">Ternary</option>
      <option value="4">Quaternary</option>
    </select>
  </td> 
</tr>
<tr>
  <td class="center"> 
    <select id="notationoption2" name="notation_to">
    <option value="2" disabled>Binary</option>
    <option value="3">Ternary</option>
    <option value="4">Quaternary</option> 
    </select>
  </td> 
</tr> 

Upvotes: 1

Related Questions