Using a select value with Javascript

Asked

Viewed 190 times

1

I need to use the value of a select in an if, at the moment I have this:

Esse seria o HTML:
    <p>Quantidade de vidas? </p>
    <select>
    <option value="vidas1" id="vidas">Mais 1000</option>
    <option value="vidas2" id="vidas">Mais 5000</option>
    <option value="vidas3" id="vidas">Menos 1000</option>
    </select>

    <p>Importancia ?</p>
    <select>
    <option value="marca1" id="marca">Pouco Importante</option>
    <option value="marca2" id="marca">Importante</option>
    </select>

    <input type="button" id="resposta" value="Calcular"/>
    <p>Resultado:<p> <span id="resultado"></span> 

Having this, I use JS to get the value of what was selected in select

Esse seria o JS:
window.onload = function(){
var btn = document.getElementById("resposta");
btn.addEventListener("click",function(){

var nomedoCliente = parseFloat(document.getElementById("nmCliente").value)
calcular(nomedoCliente);
},false);
function calcular(a){

var clienteNm = document.getElementById("nmCliente").value
var qtdeVidas = document.getElementById("vidas").value
var importanciaOp = document.getElementById("marca").value

if (qtdeVidas == "vidas1" && importanciaOp == "marca1" ) {
document.getElementById("resultado").innerHTML="<p> "+clienteNm+", identificamos que você se encontra no nivel 1</p>" 
} 
else {
document.getElementById("resultado").innerHTML="<p> "+clienteNm+"</p>"
}

However, no matter what value I put selected, it always enters the first if where it says it lies on level 1, and I don’t know what’s going on.

2 answers

2

You are using getElementById(). The method getElementById() returns the element that has the ID attribute with the specified value. However, an ID must be unique on a page. However, if there is more than one element with the specified ID, the method getElementById() will return the first element only. In your case returning only vidas1 which is the first ID he found on the page.


You can use another method to get the values, such as querySelectorAll(), or you can edit your code as follows.

<select id="vidas">
  <option value="vidas1" >Mais 1000</option>
  <option value="vidas2">Mais 5000</option>
  <option value="vidas3">Menos 1000</option>
</select>

And at the time of manipulating the select you can do so using the getElementById()

var e = document.getElementById("vidas");
var strVidas = e.options[e.selectedIndex].value;

2


Opa, the options id, must be in select, not option. Thus:

<select id="vidas">
    <option value="vidas1">Mais 1000</option>
    <option value="vidas2">Mais 5000</option>
    <option value="vidas3">Menos 1000</option>
</select>

Browser other questions tagged

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