pespantelis/vue-typeahead

Prevent auto submit form in the onHit method

hasentopf opened this issue · 2 comments

Hi, great component.
In my Laravel project, the selection via "enter" key auto submits the enclosing form. Do you know a good way to prevent this in the onHit method?
Kind regards

    import VueTypeahead from 'vue-typeahead';
    import Axios from 'axios';
    Vue.prototype.$http = Axios;

    var elem;

    export default {
        extends: VueTypeahead,
        props: ['targetInput', 'keywordCategory', 'append'],

        data () {
            return {
                src: '/api/autocomplete',
                data: {
                    query: this.query,
                    category: this.keywordCategory,
                    append: this.append
                },
                limit: 10,
                minChars: 3,
                selectFirst: true,
                queryParamName: 'search'
            }
        },

        methods: {
            onHit (item) {
                elem = document.getElementById(this.targetInput);
                if(this.append !== undefined && elem.value !== '') {
                    elem.value += this.append + item.name;
                } else {
                    elem.value = item.name;
                }
            }
        }
    }

I was on the same situation. At first it seemed to work out of the box like you mention, by preventing the default behavior to submit the form, but then, probably because I wraped the component within a <form> tag, it started the behavior you are describing.

In short, you need to override the hit method. Just put the following snippet on your component methods ie.

methods: {
     // other methods
     //....
    hit(e){
       if (this.current !== -1) {
        this.onHit(this.items[this.current])
       }
       if(e.type == "keydown" && e.key == "Enter"){
           e.preventDefault()
           this.items = []
       }
   }
}

Thanks @skarampatakis - this is a a great solution!
My version is now:

methods: {
     // other methods
     //....
    hit(e){
       if (this.current !== -1) {
           this.onHit(this.items[this.current]);
       }
       var key = e.which || e.keyCode;
       if (key === 13) { // 13 is the enter key
           e.preventDefault();
           this.items = [];
       }
   }
}