Receive id of an autocomplete option

0

I have the following autocomplete defined in HTML

HTML

<label class="input">
  <input type="text" list="list" id="entidade" placeholder="Cliente" onblur="dadosCliente ( )">
  <datalist id="list">
    @for(entidade <- entidades) {
    <option name="ent" id="@entidade.getId()" value="@entidade.getNome()">@entidade.getNome()</option>
 }
</datalist> </label>

Autocomplete is working fine, DB data is being fetched. How can I now in jQUERY get the ID of the selected element?

I have tried this: $("option[name=ent] :selected").attr('id'); but returns undefined. Any Suggestions?

    
asked by anonymous 06.02.2015 / 12:26

2 answers

1

Filling the dataList is slightly different from select, you will have to manually filter the dataList.

Below is an example with a dataList:

HTML

<input id="txtID" list="ent" />
<datalist id="ent">    
    <option id="001" value="Valor 001"></option>
    <option id="002" value="Valor 002"></option>
    <option id="003" value="Valor 003"></option>
    <option id="004" value="Valor 004"></option>
</datalist>
<button id="btGetID">Get ID</button>
<br />
<label id="lblID"></label>

JS

var btGetID = $("#btGetID");
var lblID = $("#lblID");
var txtID = $("#txtID");
var dataList = $("#ent");

btGetID.click(function () {
    var value = txtID.val();
    var option = $("option", dataList).filter(function () {
        return this.value == value;
    });
    console.log(option);
    lblID.html(option.attr("id"));
});

JSFIDDLE

    
06.02.2015 / 12:52
1

If you try to put the value of "name" in quotation marks?

$("option[name='ent'] :selected").attr('id');

Edited:

Alias, if you do function dadosCliente(){ $(this).val(); } will not work better?

Edited 2: The "only" solution I found, based on the information you passed, was:

$("#entidade").blur(function(){ var valor = $(this).val(); $("#list option").each(function(){ if( $(this).val() == valor ) console.log( $(this).attr('id') ); }); });

    
06.02.2015 / 12:34