How to capture data from a SELECT in javascript?

Asked

Viewed 185 times

-2

I’m new in the area and I’m studying. There is a project for borrowing, where requests the amount and based on the amount of installments, there is a percentage of interest. It turns out that I chose the form of SELECT to capture the benefits. But I’m not getting it. See below the html and js excerpt.

function calcular(){
    var txtvalor = document.getElementById('txtvalor')
    var opcao = document.getElementById('opcao')
    var opcoes = opcao.options[opcao.selectedIndex].value
    var valparcelas = document.getElementById('valparcelas')
    var valtotal = document.getElementById('valtotal')

    switch(opcoes.value){
        case 6:
            alert('voce escolheu 6')
        break
    }
}
<legend>Selecione o modelo de prestações:</legend>
                <select id="opcao">
                    <option value="3">3x</option>
                    <option value="6">6x</option>
                    <option value="12">12x</option>
                    <option value="18">18x</option>
                    <option value="24">24x</option>
                    <option value="36">36x</option>
                </select>

                <input type="button" value="Calcular" onclick="calcular()" class="botao">

This display result is only for test, calculation and how to display I have later.

  • The way you did it is almost correct, there were 2 errors. First error: already got the value in the variable options, IE, on the switch does not need to options.value only needs options. Second error: no case is comparing with a number 6 when what comes from select is a string, that is, just quote in the example cases '6' .

  • Opa, really, I thought I needed to assign value again, now it worked perfectly, thank you very much for the strength.

1 answer

0


Help yourself, my brother.

function calcular() {

  var opcao = document.getElementById('opcao').value;

  switch (opcao) {
    case '6':
      alert('voce escolheu 6');
      break;
  }
}
<legend>Selecione o modelo de prestações:</legend>
<select id="opcao">
  <option value="3">3x</option>
  <option value="6">6x</option>
  <option value="12">12x</option>
</select>

<input type="button" value="Calcular" onclick="calcular()" class="botao">

Browser other questions tagged

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