0

my-select is the main, when is chosen by users, it opens popup (what works right now), but what I want is that when I choose my-select2 it should change the value too.

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

<select id="my-select2">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>


document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
});

2 Answers 2

2

there is a very simple way to do that.

In the change listener, you just simply call the other select and change it's selected index after applying your own logic.

Please check the code here:

document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
  document.getElementById("my-select2").selectedIndex = this.selectedIndex;

});
<select id="my-select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

<select id="my-select2">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the fast and detailed answers , forget about eventlistener. work fine after implemented
1
document.getElementById('my-select').addEventListener('change', function() {
  console.log('You selected: ', this.value);
  selectOptionInMySelect2(this.value)
});

function selectOptionInMySelect2(value) {

  const selectElement = document.getElementById('my-select2');
  const allOptions = selectElement.options;

  for(let i=0; i < allOptions.length; i++) {

    if(allOptions[i].value == value) {
      selectElement.selectedIndex = i;
      break;
    }
  }
}

Included the same ids and values as that in your snippet. Working example here

Did not realise that an answer already got posted till the time I was editing this. Wow, community!

Just in case, the option sequence isn't the same in both selects, this will work. Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.