Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 936
Evgenij Reznik Avatar asked Mar 16 '16 15:03

Evgenij Reznik


People also ask

What does Datalist do in HTML?

The <datalist> tag is used to provide an "autocomplete" feature for <input> elements. Users will see a drop-down list of pre-defined options as they input data.

Is the Datalist tag and select tag same?

Generally, both the tags are used for choosing an option from the given list. But the main difference between both is that in the <datalist> tag the user can enter its own input and add that as an option with the help of the <input> element whereas the <select> tag doesn't provide this feature.


1 Answers

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.

like image 68
Rory McCrossan Avatar answered Sep 28 '22 12:09

Rory McCrossan