Able to use submit button for selecting top choice

I'm wondering how I can implement a submit button that works like autoselect: true so when I click submit, it selects the first suggestion.

Here is the scenario, I've started typing and then I want the user to be able to click the submit button to confirm what is 0934.

enter image description here

Upvotes: 3

Views: 70

Answers (1)

redox
redox

Reputation: 2319

The PR #101 has just been merged and released in the 0.21.4 version. With this new feature, the cursor will automatically be set on the first suggestion when autoselect: true.

You can then remember the latest selected suggestion and use it while submitting the form:

$('#contacts').autocomplete({ hint: false, autoselect: true }, [
  {
    source: autocomplete.sources.hits(indexObj, { hitsPerPage: 5 }),
    displayKey: 'name',
    templates: {
      suggestion: function(suggestion) {
        return suggestion._highlightResult.name.value;
      }
    }
  }
]).on('autocomplete:cursorchanged autocomplete:selected', function(e, sugg) {
  console.log('last', sugg);
  lastSelectedEntry = sugg;
});

$('#form').on('submit', function() {
  alert(lastSelectedEntry);
});

I've done a codepen demo.

Upvotes: 2

Related Questions