Alexander Kim
Alexander Kim

Reputation: 18401

keyup prevent modifiers - vue2

<input @keyup="fetchData(0)">

Is it possible to PREVENT modifiers (ctrl+win+cmd, etc) to work on keyup event? Just the letters and numbers.

My case: it's a name filter, when a user types a letter, list of names are updated corresponding to entered letter, but when a user presses ctrl, or ctrl+a it counts as keyup event also.

Upvotes: 0

Views: 762

Answers (1)

Michael
Michael

Reputation: 1076

You can check the keyCode from the event and trigger the fetch data method only when it's a letter or number

<input @keyup="onKeyUp($event)">

...
methods: {
    conKeyUp(e) {
        if ((e.keyCode >= 48 && e.keyCode <= 90) || (e.keyCode >= 96 && e.keyCode <= 105)) {
            // a-z or 0-9 or numpad 0 - 9
            this.fetchData();
        }
    },
    fetchData() {
        // Fetching data from server...
    }
}

An alternative method will be triggering the fetch data when the value of the field is changed like so:

<input v-model="myModel">

...
data: {
    myModel: null
},
watch: {
    myModel() {
        this.fetchData();
    }
},
methods: {
    fetchData() {
        // Fetching data from server...
    }
}

Upvotes: 1

Related Questions