In the snippet below, I have two methods to choose an item: input with datalist and traditional select with options.
The select element keeps the option values hidden, and we're still able to get it with this.value
. However, with the datalist, the value is actually displayed and the text content of the option is displayed as a secondary label.
What I'd like is to have the input+datalist approach behave like a traditional select, where "Foo" and "Bar" are shown as options that when selected have values of "1" and "2" respectively.
I've also added a repeated name "Foo" with value "3". This is to show that any solution must not depend on unique options.
You can use data-value
and jquery
to make your value hidden.
e.g:
$(document).ready(function() {
$('#submit').click(function()
{
var value = $('#selected').val();
alert($('#browsers [value="' + value + '"]').data('value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="selected" list="browsers" name="browser">
<datalist id="browsers">
<option data-value="1" value="InternetExplorer"></option>
<option data-value="2" value="Firefox"></option>
<option data-value="3" value="Chrome"></option>
</datalist>
<input id="submit" type="submit">
Thanks to @guest271314