Trigger a button click on pressing Enter in Vue
Quick tutorial on how to trigger a button click in a form on pressing Enter on keyboard in Vuejs.
In this tutorial, we will learn how we can trigger a button click function on pressing the enter button in an input field.
Let's suppose we have a page with a form to input our name.
<template> <div id="app"> <form> <input v-model="name" placeholder="Enter your Name"> <button type="submit" @click="submitForm()">Submit</button> </form> </div> </template> <script> export default { data() { return { name: "" }; }, methods: { submitForm(e) { e.preventDefault(); alert(this.name); } } }; </script>
Here, in the above code, we have a form with an input field for name and a button to submit the form.
We have added a click event on the button which gets triggered when we click the submit button.
However, here in this tutorial, we want to submit the form by pressing Enter without clicking the submit button.
Let's see how to do it below.
Submit by pressing Enter using the key modifiers in Vue
To trigger the click event on pressing Enter we have to use the key modifiers provided by Vue Js.
The key modifiers are just event modifiers but these modifiers can be used with keyboard events.
For our example, we will use the @keyup.enter modifier inside the input field of the form.
<template> <div id="app"> <form> <input v-model="name" placeholder="Enter your Name" @keyup.enter = "submitForm"> <button type="submit" @click="submitForm">Submit</button> </form> </div> </template> <script> export default { data() { return { name: "" }; }, methods: { submitForm(e) { e.preventDefault(); alert('Pressed Button',this.name); }, } }; </script>
We have added the keyup event with the enter modifier to trigger the function submitForm().
The enter modifier ensures that the function is only executed when the user releases the enter key.
Now you can press the Enter key to trigger the button click or just use the Submit button to trigger the submitForm() function.
DEMO:

Related Posts
How to get the id from the URL in Vue 3
Learn how to retrieve the URL id or slug in Vue 3 using the route object and access it in your component's template or setup function.
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
