Select second column of a datalist

0

I have a datalist that I dynamically feed and I'm adding it to the datalist element.

objJson = JSON.parse(data);
$.each(objJson, function (i, item) {
    $('#entidadesLst').append("<option  value= " + objJson[i].id + " >" + " " + objJson[i].name + "</option>");
});

I would like that when selecting an element of my datalist, it would be objJson[i].name that is seen in the field and not objJson[i].id . I want the second column to be seen and not the first one. When I speak of being "seen in the field" I mean the input that you use to write, the input of datalist .

    
asked by Lorenzo Martín 04.10.2018 в 14:24
source

2 answers

1

You can try this:

objJson = JSON.parse(data);

$.each(objJson, function (i, item) {

  $('#entidadesLst').append($("<option>").attr('value', objJson[i].name).attr("data-id",objJson[i].name));

});

Assuming that the json filled the datalist :

$("#inputEntidadesLst").on('input', function () {
  var name = $(this).val();
  var id;
  
  if($('#entidadesLst option').filter(function(){
    if($(this).val() === name){
      id = $(this).attr("data-id");
      return $(this).attr("data-id");      
    }
  }).length) {
    $(this).val(name+" "+id);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="inputEntidadesLst" list="entidadesLst">
<datalist id="entidadesLst">
  <option value="David" data-id="1">
  <option value="Carolina" data-id="2">
  <option value="Freddy" data-id="3">
</datalist> 

As you will see, I create an event input to the field where you type the name, in that event I get the typed value and compare it with the options of the datalist , if the name matches the one I'm typing I get the attribute data-id where I store the id and at the end I set the value of the field where I initially started showing you the name and the id together, you can change the order you can place the name as data-name and the id as value and it will work the same, I hope it works for you. It is an example of how to obtain pseudo attributes of a datalist .

    
answered by 04.10.2018 / 15:42
source
1
objJson = JSON.parse(data);
$.each(objJson, function (i, item) {
  $('#entidadesLst').append($("<option>").attr('value', item.name));
  $('#entidadesLst').attr("value-id", item.id);//Se agrega id como metadata para poder acceder despues a é
  console.log($('#entidadesLst').attr("value-id"));//Mostraría el id del item
});
    
answered by 04.10.2018 в 17:45