Can I make the browser show autocomplete suggestions through javascript?

I use html datalist to make autocomplete options for text input. I would like to know if instead of double-clicking on the input, if I can get the sentences to appear from javascript when the button is clicked.

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

+6
source share
2 answers

jsFiddle Demo

If you just want to show the autocomplete function on the first click, you can do some focus detection to cause it to appear. When the user clicks on the mouse, you can give input focus. The click event will bubble, and the input will be considered to have double-clicked the input, causing autocomplete to display.

 $('#grade').mousedown(function(){ if( document.activeElement == this )return; $(this).focus(); }); 
+2
source

jsFiddle Demo

It is not possible to make these suggestions appear on the input as a drop-down menu. However, you can psuedo-recreate the functionality you are looking for using jQuery .on('input API next to the div that shows the sentences.

 $('#grade').on('input focus', function(){ // show the suggestions below the text input var inp = $("#grade").val().toLowerCase(); var sgst = []; var opts = $("#gradeSuggestions")[0].options; for( var opt in opts ){ if( !opts[opt].hasOwnProperty("nodeName") )continue; if( opts[opt].value.toLowerCase().indexOf(inp) > -1 ) sgst.push(opts[opt].value); } var s = $("#suggestions"); s.html(''); for( var sg in sgst ){ var sug = $('<div>'+sgst[sg]+'</div>'); (function(val){ sug.click(function(){ $("#grade").val(val); $("#grade").focus(); }); })(sgst[sg]); s.append(sug); } }); 
0
source

Source: https://habr.com/ru/post/954535/


All Articles