how to take the value of the option that was chosen?

Asked

Viewed 322 times

0

I am a beginner in programming and I would like to know how to take the value of the selected option and put in a variable? for example, the user chooses 'Old'. and I save his choice in a variable

<select id="cmbTempo" name="cmbTempo">
    <option>Selecione:</option>
    <option value="old" >Antigas</option>
    <option value="new">Atuais</option>
    <input type="submit" name="btnOK">
</select>

3 answers

1

Imagine you have a select:

<select id="cmbTempo" name="cmbTempo">
    <option>Selecione:</option>
    <option value="old" >Antigas</option>
    <option value="new" selected="selected">Atuais</option>
    <input type="submit" name="btnOK">
</select>

To get the numeric value of the desired option do:

var element = document.getElementById("cmbTempo");
var valorSel = element.options[element.selectedIndex].value;

This will put 'new' on valorSel. If you want to pick up the text 'Current':

var element = document.getElementById("cmbTempo");
var textoSel = element.options[element.selectedIndex].text;

what will put 'Current' in the variable textSel.

0

How Voce wants to capture the value make your code so it works perfectly. Add the value of select in the click of your button ( removes the Submit input) and use the code like this:

HTML:

<select id="cmbTempo" name="cmbTempo">
    <option>Selecione:</option>
    <option value="old" >Antigas</option>
    <option value="new" selected="selected">Atuais</option>
</select>
<button type="button" name="btnOK" id="botao">gravar</button>

Now comes the javascript:

<script>

    var botao = document.getElementById('botao');
    botao.addEventListener('click',function(){
        var select = document.getElementById('cmbTempo').value;
        console.log(select);
    })

Ready, whenever you click the button a value will be inserted in the variable "select"

0


An idea would be to use onchange to set the variable as soon as the user moves the select

var select   = document.getElementById("cmbTempo");
var variavel = '';
select.onchange = function(){
    variavel = this.value;
    console.log(variavel);
}
<select id="cmbTempo" name="cmbTempo">
    <option>Selecione:</option>
    <option value="old" >Antigas</option>
    <option value="new" selected="selected">Atuais</option>
</select>

Browser other questions tagged

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