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

152
Visualizações
Change var value from dropdown in javascript with onchange

I have a dropdown list which looks like this:

<select id="cityID">
        <option value="mission">Mission</option>
        <option value="bakersfield">Bakersfield</option>
        <option value="knoxville">Knoxville</option>
</select>

And my code to get the value is:

var select = document.getElementById('cityID');
var text = select.options[select.selectedIndex].text;
text.innerHTML = cityID.value;

text.onchange = function(e) {
   text.innerHTML = e.target.value;
}

The value always chooses the first item. How can I get it to accept the cityID and change the page,

I'm sure its a formatting or typo or wrong value ?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

  1. onchange event is trigger from the select element
  2. your text variable seems to be an HTML element because you set its innerHTML property
  3. a select element has a "value" property so you don't need to get it from the selectedIndex of the options.

var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
text.innerHTML = select.value;

select.onchange = function(e) {
   textEl.innerHTML = e.target.value;
}
<select id="cityID">
        <option value="mission">Mission</option>
        <option value="bakersfield">Bakersfield</option>
        <option value="knoxville">Knoxville</option>
</select>

<p id="text"></p>

about 4 years ago · Santiago Gelvez Relatório

0

You could achieve this using addEventListener also.

var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
select.addEventListener("change", (e) => {
    textEl.innerText = e.target.value;
})
about 4 years ago · Santiago Gelvez 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