How to display only the text in datalist HTML5 and not the value?

Cerebus1504 picture Cerebus1504 · Sep 2, 2014 · Viewed 49.6k times · Source

Here is an example:

<input list="browsers" name="browser">
<datalist id="browsers">
    <option value="Internet Explorer">1</option>
    <option value="Firefox">2</option>
    <option value="Chrome">3</option>
    <option value="Opera">4</option>
    <option value="Safari">5</option>
</datalist>

http://jsfiddle.net/j7ehtqjd/1/

What I want to achieve is when I click on the input element the value would not be displayed, but ONLY the text (i.e. 1, 2, 3, 4, 5). I.e. the value should be hidden like it is with a general dropdown (<select> element).

This autocomplete feature is necessary, else I would have gone with the normal dropdown.

Answer

guest271314 picture guest271314 · Sep 2, 2014

Edit, updated

Following Regent

Try (v3)

html

<input id="selected" list="browsers" name="browser">
<datalist id="browsers">
    <option data-value="InternetExplorer" value="1"></option>
    <option data-value="Firefox" value="2"></option>
    <option data-value="Chrome" value="3"></option>
    <option data-value="Opera" value="4"></option>
    <option data-value="Safari" value="5"></option>
</datalist>
<input id="submit" type="submit">

js

$(document).ready(function() {

var data = {}; 
$("#browsers option").each(function(i,el) {  
   data[$(el).data("value")] = $(el).val();
});
// `data` : object of `data-value` : `value`
console.log(data, $("#browsers option").val());


    $('#submit').click(function()
    {
        var value = $('#selected').val();
        alert($('#browsers [value="' + value + '"]').data('value'));
    });
});

jsfiddle http://jsfiddle.net/guest271314/j7ehtqjd/13/