Search code examples
jqueryjquery-selectors

jQuery: How to get value of a particular data attribute from selected datalist (html5) option?


html:

<input list="items" id="item">

<datalist id="items">
  <option value="A item"  data-xyz = "1" >
  <option value="aa item" data-xyz = "2" >
  <option value="C item"  data-xyz = "3" >
  <option value="D item"  data-xyz = "4" >
  <option value="E item"  data-xyz = "5" >
</datalist> 

<input type="button" id="button" value="Get xyz" />

js:

$("#button").click(function(){
       alert($("#items option:selected").attr('data-xyz'));
});

link to jsbin

Query:

I just need to access the value of 'data-xyz' from selected datalist option on click of "#button" or any event.

jQuery version: 1.7.2

Thanks.


Solution

  • datalist is simply a storage for autocomplete. Since it could be used for multiple elemnts in page, it wil not have a selected property.

    You will need to locate the applicable option yourself such as the following

    $("#button").click(function() {
        var val = $('#item').val()
        var xyz = $('#items option').filter(function() {
            return this.value == val;
        }).data('xyz');
        /* if value doesn't match an option, xyz will be undefined*/
        var msg = xyz ? 'xyz=' + xyz : 'No Match';
        alert(msg)
    
    })
    

    DEMO: http://jsfiddle.net/shcRJ/