How to return a selected value in a select?

1

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 wish that when you selected you could 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 does not return something.

    
asked by anonymous 14.02.2016 / 16:54

1 answer

0

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 the two values. If you want to get the value of the option you select, use this.value . If you want to get the text inside <option> use the form 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>
    
14.02.2016 / 18:51