Submit form on textarea enter [VueJS]

Constantin Druc · 04 Mar, 2022

To submit the form when the user presses the enter key inside a textarea, you must add an event listener for the keydown event and use the .enter modifier.

1<textarea
2 v-model="form.content"
3 @keydown.enter="submit()"
4></textarea>

However, when you do that, you’ll notice a glitch; the cursor goes on to the next line before submitting the form.

To fix it, we can add a second, .prevent modifier; this will tell the browser to ignore the event and thus keep the cursor on the current line.

1<textarea
2 v-model="form.content"
3 @keydown.enter.prevent="submit()"
4></textarea>

One last problem we should probably tackle is creating new lines. We should be able to add a new line by pressing SHIFT+ENTER, but that won’t work with our current implementation; the form will just be submitted.

What we could do is go to our keydown listener and add a third modifier, called .exact . This will instruct vue to ignore any other key combinations and only call the submit() function if the enter key alone has been pressed.

However, make sure to add the .exact modifier right after the .enter modifier; otherwise, it won’t work.

1<textarea
2 v-model="form.content"
3 @keydown.enter.exact.prevent="submit()"
4></textarea>

This was tiny tip number 1; I hope you enjoyed it. Bye.