How to return a selected value in a select?

Asked

Viewed 1,493 times

2

I have this checkbox:

<select id="valores_confinamento" class ="form-control">
    <option  value="ceu" >Ceu aberto</option>
    <option value="galpao" selected>Galpão fechado</option>
</select>

And I would like that when selected it was possible to change the value in:

<div style="top: 95%; left: 34%;position: absolute">
     <span id="id_area_piquete_por_animais" ></span>
</div>

I did:

var selection = document.getElementById("valores_confinamento");
var selected = selection.options[selection.selectedIndex].text;
function valor(){
    if (selected =="ceu" ){
        document.getElementById("id_area_piquete_por_animais").innerHTML=10;
    }
    if (selected =="galpao" ){
        document.getElementById("id_area_piquete_por_animais").innerHTML=20;
    }
}
valor();
selection.addEventListener("keyup",valor);
selected .addEventListener("keyup",valor);

But it doesn’t return something.

1 answer

1


It was not very clear if what you want to display is the value or text of the option. Anyway I created a snippet with both values. If you want to get the value of the selected option, use this.value. If you want to get the text inside the <option> use the way you’re doing.

var select = document.getElementById('valores_confinamento'),
    output = document.getElementById('id_area_piquete_por_animais');

select.addEventListener('change', function() {
  output.textContent =  'Valor: '    + this.value +
                        ' / Texto: ' + select.options[select.selectedIndex].text;
});
<select id="valores_confinamento" class="form-control">
  <option value="ceu">Ceu aberto</option>
  <option value="galpao" selected>Galpão fechado</option>
</select>

<div style="top: 95%; left: 34%;position: absolute">
  <span id="id_area_piquete_por_animais"></span>
</div>

  • Thank you Renan, just what I wanted!

  • 1

    marquei, thank you very much!

Browser other questions tagged

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