Is it possible to capture the index of a selected select?

Asked

Viewed 55 times

0

Simply put, I have a select (combobox) in my html and would like to know which Input (position) has been chosen. that is, if it was the first, the second, the third... The reason is that in my ajax I receive an array of products, and the "price" field will receive the value depending on the selected select. HTML:

<select class="form-control" id="selectProdutos">
   <option selected>Escolha uma opção</option>
 </select>

Javascript:

for (var i = 0; i < data.length; i++) {
         $('#selectProdutos').append('<option>' + data[i].descricao + '</option>');
      }
  • 1

    You should include a property value in its elements <option>, then just get the value of <select>, which will have the same value as <option> selected.

  • You saved my night, thank you very much. I don’t know how to enjoy or accept your answer

1 answer

1

Items on your list need to have the attribute value to work

<select class="form-control" id="selectProdutos">
    <option value="null" selected>Escolha uma opção</option>
    <option value="Opcao 1">Opção 1</option>
    <option value="Opcao 2">Opção 2</option>
    <option value="Opcao 3">Opção 3</option>
</select>

In javascript you can access the input value like this:

var lista = document.getElementById("selectProdutos");
var valor = lista.value;
console.log(valor);

list.value returns the value of your select at any given time. Console.Log() is used to send this value to the console for viewing. I hope you have solved, any doubts just call. :)

Browser other questions tagged

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