Get the value of a select dynamic

3

I would like to know how I get the value of a <select> dynamic, ie when I modify the value it presents me with this value, I imagine something like below, could anyone help me?

varItens = document.getElementById('caminhos');

for( i = 0;i < varItens.length;i++)
{ 
  varItens.options[i].selected = true; 
   alert( varItens.options[i].id );
}

But it does not work, because I know this would be static.

    
asked by anonymous 08.12.2015 / 17:14

3 answers

5

See if this helps you:

$("#caminhos").on('change', function(e){
  alert($(this).val())
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="caminhos">
  <option value="Elemento 1">Elemento 1</option>
  <option value="Elemento 2">Elemento 2</option>
  <option value="Elemento 3">Elemento 3</option>
  <option value="Elemento 4">Elemento 4</option>
  <option value="Elemento 5">Elemento 5</option>
</select>
    
08.12.2015 / 17:19
2

I saw that you already accepted a response with jQuery. Here's one with native JavaScript:

var items = document.getElementById('caminhos');
items.addEventListener('change', function(){
    alert(this.value); // o valor que procuras é: this.value
});

If the element was not present yet you need to delegate, this is easy:

var items = document.getElementById('minhaDiv'); // elemento presente desde inicio
items.addEventListener('change', function(e){
    if (e.target.id == 'caminhos') alert(e.target.value); // o valor que procuras é: e.target.value
});

In this case it is not worth using jQuery.

    
08.12.2015 / 18:06
0

I do this in the following way each time your select is selected or you select the value by a function that is called in the onchange or when changing this value is stored in a variable.

    
08.12.2015 / 17:35