Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I trigger the browser to show autocomplete suggestions via javascript?

I am using the html datalist to make autocomplete options for a text input. I would like to know if rather than double clicking on the input if I can trigger the suggestions to appear from javascript when a button is clicked on.

<datalist id='gradeSuggestions'>
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
</datalist>

<input name="grade[]" autocomplete="off" list='gradeSuggestions' type='text' />

<input type='button' id='showSuggestions' value='Show Suggestions' />

<script>
$('#showSuggestions').on('click', function(){
   // show the suggestions below the text input 
});
</script>

Here is a jsFiddle

like image 233
Mike Avatar asked Sep 24 '13 20:09

Mike


1 Answers

jsFiddle Demo

If you merely want to show the autocomplete feature on the first click, then you can do some focus detection to trigger it to appear. When the user depresses the mouse on the input, you can give the input focus. The click event will bubble and the input will think that the input was clicked twice causing the autocomplete to show.

$('#grade').mousedown(function(){
 if( document.activeElement == this )return;
 $(this).focus();
});
like image 109
Travis J Avatar answered Sep 22 '22 23:09

Travis J