-1

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?

Martijn Vissers
  • 712
  • 5
  • 29
alexcr
  • 171
  • 1
  • 12
  • 3
    Does this answer your question? [How do I programatically select an HTML option using JavaScript?](https://stackoverflow.com/questions/10911526/how-do-i-programatically-select-an-html-option-using-javascript) or [HTML SELECT - Change selected option by VALUE using JavaScript](https://stackoverflow.com/questions/12265596/html-select-change-selected-option-by-value-using-javascript) or [How to change the current selected option in the – caramba Apr 30 '22 at 16:19
  • Can you add the HTML code in the question description please? The first solution you've given looks right although I couldn't know for sure until I see the HTML – BrunoT Apr 30 '22 at 16:21
  • or [set option "selected" attribute from dynamic created option](https://stackoverflow.com/questions/4590311/set-option-selected-attribute-from-dynamic-created-option) – caramba Apr 30 '22 at 16:21

1 Answers1

0

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>
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28