afcapel / stimulus-autocomplete

Stimulus autocomplete component
MIT License
482 stars 63 forks source link

Auto-select/highlight the first result on "data load ended" #114

Open StanBright opened 2 years ago

StanBright commented 2 years ago

Hey, many thanks for this "simple" and effective stimulus controller.

I've been replacing ReactSelect throughout my apps with it.

However, there's still some UX that's bugging me. I'd like to have the first result automatically highlighted so that the user can press enter and select it. A good example is GitHub's search box in the navbar here.

Any ideas what's the easiest way to achieve that?

Thanks, Stan

apsylone commented 1 year ago

That's a nice question, it would "force" a selection. I wanted this kind of selection or on "focus out", make the field blank for forcing html5 required validation. Any clues on how to do this ? Ping @afcapel

StanBright commented 1 year ago

@apsylone did you manage to find a solution :)?

thomasbrus commented 4 months ago

@StanBright Here you go

import { Autocomplete as StimulusAutocomplete } from 'stimulus-autocomplete';

export default class Autocomplete extends StimulusAutocomplete {
  replaceResults(html) {
    super.replaceResults(html);
    this.maybeSelectFirstOption();
  }

  maybeSelectFirstOption() {
    if (!this.selectedOption && this.options.length > 0) {
      this.select(this.options[0]);
    }
  }
}