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

Categories

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.

<input list="options" onchange="console.log(this.value)"/>
<datalist id="options">
  <option value="1">Foo</option>
  <option value="2">Bar</option>
  <option value="3">Foo</option>
</datalist>

<select onchange="console.log(this.value)">
  <option value=""></option>
  <option value="1">Foo</option>
  <option value="2">Bar</option>
  <option value="3">Foo</option>
</select>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...