'Change the selected option in select with only javascript

I'm trying to change the selected option of a select, I have already tried this way:

document.getElementById("myselect").value = "1";

and also 

document.getElementById("myselect").selectedIndex = 1;

but with the first one, it doesn't work, instead of changing to the option with the value 1, it goes to the last option of the select, and with the second one it doesn't work at all. Any suggestions?



Solution 1:[1]

You can use both value and selectedIndex but the usage is different, check the example below to understand how to use them.

const select = document.getElementById("select");
const options = document.querySelectorAll("select option");

// Using selectedIndex
document.getElementById("btn").addEventListener("click", () => {
  const nextIndex = select.selectedIndex + 1;
  select.selectedIndex = nextIndex % options.length;
});

// Using value
document.getElementById("orange-btn").addEventListener("click", () => {
  select.value = "orange";
});
<select value="apple" id="select">
  <option value="apple">Apple</option>
  <option value="mango">Mango</option>
  <option value="orange">Orange</option>
  <option value="kiwi">Kiwi</option>
</select>

<button id="btn">Next Option</button>
<button id="orange-btn">Select Orange</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anonymous Panda