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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…