Home > Blockchain >  Is there a way to distinguish selecting from a datalist vs typing the same string manually?
Is there a way to distinguish selecting from a datalist vs typing the same string manually?

Time:08-26

As far as I can tell there isn't, but I figured I'd ask.

I have a text input. Autocomplete suggestions are fetched dynamically as you type and fill a datalist attached to the input. Normally, typing something and pressing the "search" button brings up a table of search results to select from.

Since the datalist is basically the exact same thing, but simplified, and selecting an option from it is unambiguous, I'd like it to just carry on with my selection handlers without having to bring up the list for selection a second time. When the person manually types something though, I still want them to explicitly pick from the list, especially since some options may be substrings of the others, so I don't want it to auto-select a result for you if it matches halfway through.

CodePudding user response:

I ended up not reimplementing it like ControlAltDel suggested in his comment and instead went with the following slightly hacky but functional solution:

Since I am refetching the search results as you type, if only 1 search result is returned (ie. it's unambiguous) and the current string is a case-insensitive exact match to that result, then select it. It works well for what I need it for, but I could imagine this not working for everyone.

The JS is roughly as follows:

if (searchResults.length === 1
    && searchString.toLowerCase() === searchResults[0].toLowerCase()
) {
    selectResult(searchResults[0]);
}

I'm calling this in my handler for when the search results list changes, not the input's handler, since the results are only re-fetched after the input has already been changed.

  • Related