How to cancel a keypress

I’m watching an input field for keystrokes.
I have a date field and I want to increment the date by 1 if the user hits the + key.

My logic is all worked out but I have one problem…

If the user types 1/1/2010 and hits plus, the vue model has been updated to read ‘1/1/2010+’

Is there a way to cancel the keystroke in code?

something like

if (keystroke == "+")
{
  keystroke.cancel;
  // other logic
}

Solved this - answer below for anyone who needs it.

<div id="app">
   <input v-on:keydown="keyhander" v-model=...>
</div>

var app = new Vue({
  el: '#app',
  data: { ...},
  methods: {
   keyhandler: function(event) {
   if (event.key == "+")
   {
      // do something
    event.preventDefault();
   }
3 Likes

Just as a helper, I played a bit with VueJS Event Modifiers.
https://jsfiddle.net/1dp8hjkt/

HTML (107 is ‘+’ keyCode)

<div id="app" v-on:keydown.107.capture.prevent.stop>
  <input v-on:keydown="keyhandler" />
</div>

JS

new Vue({
  el: '#app',
  methods: {
    keyhandler(event) {
      alert(`you didn't type '+', did you?`);
    },
  },
});

Hey Elfayer, this is great!
While my solution above worked, I’m running into another issue where some code is being triggered that I don’t understand, I’ll see if your approach might fix it.

I played with the .capture.prevent.stop briefly, but didn’t get it working.

Here’s a link to the question on the double trigger: Extra event being triggered, how to stop?

I’ll tinker with it more tonight, hopefully someone will spot my error and set me straight!

You should edit your answer to fix the assignment typo in case somebody does a copy-paste.

This:

if (event.key = "+")

Should be:

if (event.key === "+")
1 Like