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/
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With