The two import issues are:
- Create a dom element that looks like the drop-down button next
to a textfield and add listeners that will trigger the
open/close of the item list.
- Create the autocomplete with minLength 0. The default is 1 which means without it the item list will only show after 1 character is entered.
My HTML:
<input type="text" id="shop" autocomplete="off"/><a role="button" class="autocmpleteShowAllButton" title="Show All Items" tabindex="-1">⏷</a>
The input provides the textfield for editing/showing an entry
while the link simulates the button to open/close the item list.
It is very import to not have any whitespace between the input and
the link or there will be an ugly gap on screen. For the link I've
added this CSS:
.autocmpleteShowAllButton {
border: 1px solid rgb(204, 204, 204);
padding-left: 0.4em;
padding-right: 0.4em;
background: rgb(246, 246, 246)
url("images/ui-bg_glass_100_f6f6f6_1x400.png") repeat-x scroll 50% 50%;
padding-top: 0.1em;
padding-bottom: 0.15em;
cursor: pointer;
}
The background image is part of jqueryui. Please note that the
down arrow of the "button" is the text in the link: ⏷.
See the html code for this element: ⏷
Here is my JavaScript to make it work. Please note that this is
an internal project to learn ES 6.
let shopSource = this.shops.map(s => s.name);
let shopAutocomplete = $('#workingArea').find('#shop').autocomplete({
minLength: 0,
source: shopSource
});
let wasOpen = false;
$('#workingArea').find('.autocmpleteShowAllButton').mousedown(()=>{
wasOpen = shopAutocomplete.autocomplete( "widget" ).is( ":visible" );
});
$('#workingArea').find('.autocmpleteShowAllButton').click(()=>{
shopAutocomplete.focus();
if ( wasOpen ) {
return;
}
shopAutocomplete.autocomplete( "search", "" );
});
At first I make the textfield "shop" an autocomplete field.
The mouse listener is used to determine if the item list was
visible. This is used in the click listener that is called later
(a click needs a mouse up). With the focus there is an implicit
close of the suggestion popup. So the return will take care that
it stays closed when it was previously opened.
When the item list was previously closed the
autocomplete("search","") will open it (unless you've forgot
minLength:0. Then it will do nothing).