Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Get data attribute of Datalist

I load some hidden data into a datalist and bind it with the data attribute.

If a value selected, I want to get the value of the corresponding data attribute. This is my code:

<input list="browser" id="number">
<datalist id="browser">
    <option data-customValue="Abc" value="Firefox">1</option>
    <option data-customValue="Def" value="Chrome">2</option>
    <option data-customValue="Ghi" value="Explorer">3</option>
</datalist>
$('#number').on('input', function() {
    var value = $('#browser').val();
    alert($('#browsers [value="' + value + '"]').data('customValue'));
});

In my case, I only get undefined as a response.

Here is the fiddle: https://jsfiddle.net/bd4rpztk/1/

Upvotes: 7

Views: 11387

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

There's two issues in your code. Firstly you need to get the val() from the input element, not the datalist. Secondly data attribute names should be lowercase otherwise it interferes with jQuery's internal cache. With that in mind, try this:

<input list="browser" id="number">
<datalist id="browser">
    <option data-customvalue="Abc" value="Firefox">1</option>
    <option data-customvalue="Def" value="Chrome">2</option>
    <option data-customvalue="Ghi" value="Explorer">3</option>
</datalist>
$('#number').on('input', function() {
    var value = $(this).val();
    alert($('#browser [value="' + value + '"]').data('customvalue'));
});

Working example

Note that your logic may need to be amended to cater for people who are typing a value directly in to the input.

Upvotes: 8

Related Questions