Take the value of a dynamic select

Asked

Viewed 13,886 times

3

I wonder how I get the value of a <select> dynamic, ie when I modify the value it presents me this value, I imagine something like below, someone could 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 doesn’t work, because I know this was if it was static.

  • 1

    Do you want to take the value selected by the user or all the values of the select? In your example you are trying to select everyone and trying to display the ID of option, that will probably always be null.

  • would be from each option when it was selected

  • To do this the @Danilo answer is correct, as long as you can use jquery, as it is in the question tags.

3 answers

6


See if that 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>
<select id="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>

  • 1

    thanks for the answer, I ended up remembering that because being dynamic I was just passing the way of the div and after the option ex: $('myDiv'). on('change','#paths',Function() { });

  • So did that answer fit you? Very good :D

  • served yes, thank you

  • @Danilo I think you should add the delegation to the reply: $('minhaDiv').on('change','#caminhos',function(){ that was the original problem of the question.

4

I saw that you already accepted an answer with jQuery. Here is 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 yet present you need to delegate, that’s 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.

0

I do it as follows each time your select is chosen or you are selected by the value by a function that is called in the onchange or when changing this value is stored in a variable.

  • You can show us your way with codes?

Browser other questions tagged

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