I want to reverse 2 selectors between them and my function doesn’t work

How can I fix this? I have practically 2 selectors with the same values, and I want to make sure that when I press a button, the first selector takes the value of the second selector and the second selector takes the value of the first. But my function doesn’t work. In short, I want to invert the values ​​of the 2 selectors between them.

function myFunction() { 

    var test = document.getElementById("selector1").selectedIndex;
    var test2 = document.getElementById("selector2").selectedIndex;

    document.getElementById( 
      "selector1").selectedIndex = "test2";

    document.getElementById( 
      "selector2").selectedIndex = "test";

}

Answer

You are mostly correct, you just have some errors with setting the selectedIndex – you aren’t using your variables test & test2:

function myFunction() {
  var test = document.getElementById("selector1").selectedIndex;
  var test2 = document.getElementById("selector2").selectedIndex;

  document.getElementById(
    "selector1").selectedIndex = test2;

  document.getElementById(
    "selector2").selectedIndex = test;
}
<select id='selector1'>
  <option value='one'>one</option>
  <option value='two'>two</option>
  <option value='three'>three</option>
  <option value='four'>four</option>
  <option value='five' selected='selected'>five</option>
</select>
<select id='selector2'>
  <option value='one'>one</option>
  <option value='two'>two</option>
  <option value='three' selected='selected'>three</option>
  <option value='four'>four</option>
  <option value='five'>five</option>
</select>
<button onclick='myFunction()'>Invert
</button>

Leave a Reply

Your email address will not be published. Required fields are marked *