Using the value of a select with Javascript

Asked

Viewed 48 times

1

I would like to know how to use the index of a select, for example I have select below

function verificartime() {
  let time = window.document.getElementsByName("time")
  let restime = window.document.getElementById("restime")

  // se o time selecionado for o indice[1] então restime.innerHTML="Palmeiras"
  // se o time selecionado for o indice[2] então restime.innerHTML="Corinthians" e assim por diante


}
<select name="time">
  <option>Selecione seu time</option>
  <option value="palmeiras">Palmeiras</option>
  <option value="corinthians">Corinthians</option>
  <option value="saopaulo">São Paulo</option>
  <option value="santos">Santos</option>
</select>
<input type="button" value="Time" onclick="verificartime()">
<div id="restime">
  Aqui vai o resultado do select
</div>

I would like to select any team that returns the value in the div

NOTE: I am trying several ways looking on the net but I can’t find a way to perform it,

1 answer

1

One of the ways I could do it is to remove the window, leave only the Document that will already work. Change the getElementsByName and use the getElementById same, and change the property name down in the select for id also. Then just use the innerHTML in div that you recovered with the getElementById. See if this solves:

function verificartime() {
  let time = document.getElementById("time")
  let restime = document.getElementById("restime")

  /*aqui você consegue acessar o text do option, se quiser o value dele,
  só usar time.value; */
  var timeSelecionado = time.options[time.selectedIndex].text;
  
  restime.innerHTML = timeSelecionado;
}
<select id="time">
  <option>Selecione seu time</option>
  <option value="palmeiras">Palmeiras</option>
  <option value="corinthians">Corinthians</option>
  <option value="saopaulo">São Paulo</option>
  <option value="santos">Santos</option>
</select>
<input type="button" value="Time" onclick="verificartime()">
<div id="restime">
  Aqui vai o resultado do select
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.