I am trying to automatically show all options of a datalist html5 element to the user when a button is clicked bringing the input element into focus. Normally, all options are shown when the user clicks on the associated text input element twice. I would like to programmatically simulate this behavior so that the user can see all options before they start typing.
I have tried simulating clicks and double clicks by getting focus using $('#text-input').focus();
(this works) and then using jquery .click()
(once and twice), .dblclick()
, .trigger('click')
and even using jquery.simulate.js. All of these trigger the $('#text-input').click(function() {...});
but do not actually affect the state of the visible input element in the browser.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="main">
<form>
<datalist id="categories">
<option value="travel">
<option value ="work">
<option value="literature">
<option value="teaching">
</datalist>
<input type="text" list="categories" id="text-input">
<button type="button" id="mic-button">
</button>
</form>
</div>
</body>
</html>
And my code with the dblclick attempt:
(function($) {
$(document).ready(function() {
var textInput = $('#text-input');
textInput.dblclick(function() {
alert('Handler for .dblclick() called.');
});
$('#mic-button').click(function() {
textInput.focus();
// list all the options by tricking the datalist
// to think the user double clicked on it
textInput.dblclick();
});
})(jQuery);
This feature is not currently defined in the spec, as nice as it would be.
See the following issue, as it touches on the same problem you're describing: Programmatically make datalist of input[type=url] appear with JavaScript
来源:https://stackoverflow.com/questions/17582980/html5-datalist-simulate-a-click-event-to-expose-all-options