How to get the value and label of a datalist using jquery?

0

I have a datalist , which I use like this:

<input id="estabelecimento" list="listaEstabelecimento"/>
<datalist id="listaEstabelecimento">
  <option value="valor1" label="label1"></option>
</datalist>

I use this component to make the autocomplete effect. In the code, I use $("#estabelecimento").val() to filter the data. Using $("#estabelecimento").val() it returns me label1 . How do I get valor1 ? I need it too.

    
asked by anonymous 09.07.2017 / 18:36

1 answer

0

Actually, the $("#estabelecimento").val() command returns what is inside value . It looks like you want to return what's inside the label of the datalist option object. You can scroll through the options within the datalist object by using a for and comparing the values, as below:

$("#estabelecimento").change(function(){

  var valor = $("#estabelecimento").val();
  var label;
  
  var options = document.getElementById("listaEstabelecimento").options;
  
  for(var i = 0; i < options.length; i++) {
    
    if(options[i].value == valor) {
      label = options[i].label;
    }
    
    if(label != null) break;
    
  }
  
  console.log("Valor: " + valor + ", Label: " + label);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="estabelecimento" list="listaEstabelecimento"/>
<datalist id="listaEstabelecimento">
  <option value="valor1" label="label1"></option>
</datalist>
    
29.06.2018 / 22:31