Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda