Josh
Josh

Reputation: 1

How do get focus to return to input on selection with enter

Using Vue Multiselect to create an unordered list, how would I get the focus to return to the input when a user hits enter to select an item? That is:
1. user searches item
2. user hits enter
3. item is added to list (as currently happens)
4. focus is returned to input with dropdown closed so the user can type in a new entry.

Would be amazingly grateful for any help :)

I’ve tried changing close-on-select to false which returns the focus correctly but leaves the dropdown open, which is not ideal as it hides the content below.

https://jsfiddle.net/hugodesigns/rtogxe4s/?utm_source=website&utm_medium=embed&utm_campaign=rtogxe4s

new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    options: [

    ],
    optionsProxy: [],
    selectedResources: [],
    showLoadingSpinner: false
    },
  methods: {
    customLabel (option) {
      return `${option.name} - ${option.version}`
    },
    updateSelected(value) {
      value.forEach((resource) => {
        // Adds selected resources to array
        this.selectedResources.push(resource)
      })
      // Clears selected array
      // This prevents the tags from being displayed
      this.optionsProxy = []
    },
    cdnRequest(value) {
        this.$http.get(`https://api.cdnjs.com/libraries?search=${value}&fields=version,description`).then((response) => {
        // get body data
        this.options = []
        response.body.results.forEach((object) => {
          this.options.push(object)
        });
                this.showLoadingSpinner = false
      }, (response) => {
        // error callback
      })
    },
    searchQuery(value) {
        this.showLoadingSpinner = true
        // GET
      this.cdnRequest(value)
    },
    removeDependency(index) {
      this.selectedResources.splice(index, 1)
    }
  },
  created() {
    const value = ''
    this.cdnRequest(value)
  }
}).$mount('#app')

Current result is that an item is added to the list and the multiselect loses focus, so must be clicked again to enter more input.

Expected behaviour is that an item is added to the list and focus returns to the multiselect, ready to accept input, with dropdown closed.

Upvotes: 0

Views: 1559

Answers (1)

Cathy Ha
Cathy Ha

Reputation: 1677

It seems like dropdown opening on focus is a behavior was flagged as an issue for version 2. If you upgrade the package the dropdown will not automatically open on focus. https://github.com/shentao/vue-multiselect/issues/740

You should be able to get the element to go into focus by adding a ref to the multiselect and doing the following:

this.$refs.multiselectref.$el.focus();

Upvotes: 1

Related Questions