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

Asked

Viewed 737 times

0

I have a datalist, that I wear like this:

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

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

  • That one datalist is associated with a input, right? So why are you taking the value of datalist and not of input?

  • I wrote it wrong, I use it the same way I changed it now

2 answers

1

In fact, the command $("#estabelecimento").val() returns what is inside value. It seems you want to return what’s inside the label of the datalist option object. You can browse the options within the datalist object 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>
<input id="estabelecimento" list="listaEstabelecimento"/>
<datalist id="listaEstabelecimento">
  <option value="valor1" label="label1"></option>
</datalist>

0

Very simple form:

//Listando apenas um valor, clicando sobre o option:
$("#estabelecimento").on('change', function() {

  var _this = $(this);

  $('#listaEstabelecimento').find('option').each((index, el) => {

      if (_this.val() === el.value) {

          prompt('', el.value + ' ' + el.label);

      }

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="estabelecimento" list="listaEstabelecimento" />
<datalist id="listaEstabelecimento">
  <option value="valor1" label="label1"></option>
  <option value="valor2" label="label2"></option>
  <option value="valor3" label="label3"></option>
</datalist>

Browser other questions tagged

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