[How to] Programmatically select the first suggestion on tab or blur from input
See original GitHub issuevue-autosuggest
version: ^1.8.1node
version: v8.11.2npm
(oryarn
) version: npm 6.1.0
Description:
Sorry, this is likely not a bug, but I am having some trouble doing something with the component.
I’m trying to automatically select the first suggestion on a blur or tab event from the input, so that the input element is given a value, the suggestions dialog is closed, and the selected variable is set to the first suggestion object – as if the first item were clicked. (I’d only do this if a value was not chosen/assigned.)
The use case is: typing in three letters, then immediate tabbing out without selecting a suggestion, should act as if the first suggestion were clicked.
What is the recommended way to do this? I can call setChangeItem using a ref, but it does not change the input value. I can set searchInput using a ref, but that triggers a change and does another lookup leaving a new dropdown opened. I thought I might even try triggering a click on the first element, but that’s not going to work either.
Similarly, a second but related issue I’m having - when backspacing to delete all characters of the input, I’d like to make the value and selected object be empty. It’s not, so vee-validate will still see the field as non-empty after erasing all input from it after previously having a selection.
How can I automate selecting a suggestion when there are suggestions, as if it were clicked? How can I fully “reset” a selection to a blank slate?
Relevant code or config:
// attributes on vue-autosuggest
ref="autosuggest"
@blur="blurHandler"
@keydown.tab="tabHandler"
.
.
// snippets from methods
// trying to "reset" selected (& value, but not sure how) when there are no suggestions
fetchResults(val) {
if (!val || (val.length < 2)) {
this.suggestions = [];
this.selected = null;
return;
}
.
.
.
}
// trying to auto-select the first suggestion three different ways
tabHandler(e) {
/*
let item = this.$refs.autosuggest.getItemByIndex(0);
this.$refs.autosuggest.setChangeItem(item, true);
this.suggestions = [];
*/
/*
const element = this.$el.querySelector('#autosuggest__results_item-0');
element.click();
*/
/*
let item = this.$refs.autosuggest.getItemByIndex(0);
this.$refs.autosuggest.searchInput = item;
*/
},
Any advice here would be very much appreciated! Thanks for the component. 😃
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
ah yes I thought you’d want to tab then hit enter to select. This is not ideal, but here’s the solution. I will make sure 2.0 I’m currently iterating on has something a bit more ergonomic. Open to suggestions.
Updated the codesandbox.
Yes! This is what I was looking for. I was close, but missing the listeners.selected(true).
Thanks for considering this case for v2.