afcapel / stimulus-autocomplete

Stimulus autocomplete component
MIT License
478 stars 61 forks source link

Pressing down key should open select #145

Open brentgreeff opened 8 months ago

brentgreeff commented 8 months ago

Ideally - I would like to see ALL the options available when pressing the down key.

If there is text in the box - but the list-group-items are hidden, then it shows them again.

If there is no text in the input - it sends a request to the server with no value for q

In my usecase, there are only a few potential values, at most about 10 - so seeing all of them is useful.

Lxxrxns commented 5 months ago

Isn't there a way to programmatically trigger the search?

I would like to have it search automatically when a value is inserted into the input field by some other javascript code (like a button press), but haven't been able to figure out how...

I tried autocomplete.trigger("change") but this didn't do anything :/

Anyone got any ideas? Because that could also easily translate to a solution to your question, e.g. we could bind a down-arrow key (or any other trigger) to the programmatical showing of the search results.

Lxxrxns commented 5 months ago

Update:

Added a single line of code to the autocomplete.js file to allow external (programmatic) triggering of the search:

Add this to the connect() function in autocomplete.js:

document.addEventListener("doSearch", this.onInputChange);

Then, in your website/app, you can trigger this event manually by doing:

const event = new Event("doSearch"); 
document.dispatchEvent(event); 

For example, if you want to trigger the search on a keyboard arrow down press, in jQuery you could do:

$('#yourInputField').keydown(function(e){
  if (e.keyCode==40){
    const event = new Event("doSearch"); 
    document.dispatchEvent(event); 
  }       
});

And voila, pressing arrow down in your input field (with id="yourInputField") will trigger the search.

It's a bit hacky, but I'm not a javascript expert.