Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form submitting when pressing enter from a text input, using Vue.js

I am using Vue.js in my app and have a text input within a form

<div id="myVueForm"> <form>    <input type="text" v-on="keyup:addCategory | key 'enter'">     <!-- more form fields -->    <button type="submit">Submit Form</button> </form> </div> 

In my Vue instance I have the following

new Vue({     el: '#myVueForm',      methods: {         addCategory: function(e)         {            if(e) e.preventDefault();            console.log("Added a new category, thanks!");         }     } }); 

Despite the preventDefault() call, when a user presses enter whilst on the text input the form still submits (although the addCategory() method does fire). This behaviour can be demonstrated in this fiddle.

I know I can use jQuery to catch the event and prevent the submit, but I'd like to see if it's possible in Vue to do this as it seems quite a common usage.

like image 270
harryg Avatar asked Jun 26 '15 10:06

harryg


People also ask

How do I stop form submit on Enter key press?

getElementById("testForm"); form. addEventListener("submit",function(e){e. preventDefault(); return false;}); This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

How do I stop a Vue submit form?

The other way we can achieve preventing the default form submission behaviour is by attaching a submit event with the prevent modifier to the starting form tag in the template. This will prevent the page from reloading when the submit button is pressed as well.

How do I stop form submitting?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting. Example: HTML.

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.


2 Answers

Here's a solution for Vue.js 2.x:

<input type='text' v-on:keydown.enter.prevent='addCategory' /> 
like image 112
bradlis7 Avatar answered Sep 29 '22 06:09

bradlis7


The submit is always fired on keydown. So use keydown instead of keyup.

<input type="text"  v-on="keydown:addCategory | key 'enter'"> 
like image 29
Sebastian Nette Avatar answered Sep 29 '22 08:09

Sebastian Nette