Use value of a select with JavaScript

1

I need to use the value of a select in an if, I currently 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 the 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 goes into the first if where it says it is at level1, and I do not know what's going on.

    
asked by anonymous 11.12.2018 / 19:03

2 answers

2

Oops, the id of the options, should be in the select, not the option. So:

<select id="vidas">
    <option value="vidas1">Mais 1000</option>
    <option value="vidas2">Mais 5000</option>
    <option value="vidas3">Menos 1000</option>
</select>
    
11.12.2018 / 19:12
2

You are using getElementById() . The getElementById() method returns the element that has the ID attribute with the specified value. But an ID must be unique on a page. However, if there is more than one element with the specified ID, the getElementById() method 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 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 select you can do this using getElementById()

var e = document.getElementById("vidas");
var strVidas = e.options[e.selectedIndex].value;
    
11.12.2018 / 19:10