mesqueeb's avatar

How to detect shift enter on a form in Vue?

So I have a form with only one text area inside. On the form itself I have:

@submit.prevent="addNew(thing)"
@enter="addNew(thing)"

However, when launching the function addNew() I want to be able to recognize Shift. I tried adding additional window listeners etc. but it get's a mess!

I tried adding event listener with this inside, but it doesn't recognize 'shiftKey' somehow:

if (e.shiftKey){
return;
}

What I want to achieve: Make shift enter do a new line in the text area, but make normal enter submit the form.

0 likes
2 replies
mesqueeb's avatar

Solved it with putting a window watcher into my vue component but that only triggers on the specific textarea, which I marked with a certain ID, different for each component.

This code below is in my component.

ready(){
let vm = this;
    let form = "#new-under-"+this.thing.id+">textarea";
    window.addEventListener('keydown', function(e) {
        if ( $(form+':focus').length > 0 ) {
          // INPUT AREAS IN FOCUS
          switch(e.keyCode) { 
            case 13:
                if (e.shiftKey){
                    console.log('shift enter');
                    break;
                }
                console.log('normal enter');
                e.preventDefault();
                vm.addNew();
                break;
          } // end switch
        }
    });
},

Please or to participate in this conversation.