Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...