HTML:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42">The answer</option>
<option data-value="1337">Elite</option>
<option data-value="69">Dirty</option>
<option data-value="3">Pi</option>
</datalist>
<input type="hidden" name="answer" id="answer-hidden">
jq:
$('input[list]').on('input', function(e) {
var $input = $(e.target),
$options = $('#' + $input.attr('list') + ' option'),
$hiddenInput = $('#' + $input.attr('id') + '-hidden'),
label = $input.val();
$hiddenInput.val(label);
for(var i = 0; i < $options.length; i++) {
var $option = $options.eq(i);
if($option.text() === label) {
$hiddenInput.val( $option.attr('data-value') );
break;
}
}
});
来源网站:http://www.coderlord.com/javascript/3/4/0/43FC1F29884340.html