`@keyup.enter event listener will only be triggered upon pressing the Enter key if the focus is on

My login button only seems to work when I press the tab button after entering my email and password. I would like it to work whenever I press the enter key while on the Login page of this VueJS application.

This is the HTML template:

<template>
    <div class="login-page" id="login-page">
        <div class="form" id="form">
            <form class="login-form" id="login-form">
                <div class="head-login">
                    <img class="teamfu-image" src="../assets/teamfu-v.png"/><h2 class="login">Login</h2>
                </div>
                <hr class="beneathBorder" color="white">
                <div>
                    <p class="text">Email: <input v-model="input.email" class="input" type="text" placeholder='e.g. [email protected]' /></p>
                    <p class="text">Password: <input v-model="input.password" class="input" type="password" placeholder=" " /></p>
                </div>
                <button type="button" @click="login" @keyup.enter="login"" > Login</button>
                <p class="message">Not a part of the team? <router-link class="reg" :to="'/register'">Register</router-link></p>
            </form>
        </div>
    </div> 
</template>

This is the script:

<script>
import { checkUser } from "../db/storage";

export default {
    name: 'login-page',
    data() {
        return {
            input: {
                email: '',
                password: ''
            }
        };
    },
    methods: {
        login() {
            if (this.input.email !== "" && this.input.password !== "") {
                if (checkUser(this.input.email, this.input.password)) {
                    this.$emit("authenticated", true);
                    this.$router.replace('/dashboard');
                } else {
                    alert("The username and/or password is incorrect");
                    console.log("The username and/or password is incorrect");
                }
            } else {
                alert("A username and password must be present");
                console.log("A username and password must be present");
            }
        }
    }
};
</script>

Answer №1

To implement a page-level keyup handler, be sure to place it as high up in your element hierarchy as possible:

<div class="main-page" @keyup.enter="submitForm" id="main-page">

Answer №2

To optimize the functionality, it is recommended to utilize the submit event of the form in order to trigger the login() function instead of relying on click or keyup event handlers on the button. The <form> element will automatically generate the submit event when the user clicks on the submit button within the form, or if they press ENTER while the form is active.

Start by converting the button into a submit type and eliminating the current click/keyup handler:

<!-- ❌
<button type="button" @click="login" @keyup.enter="login">Login</button>
-->
<button type="submit">Login</button>

Next, include a submit handler within the form:

<form @submit.prevent="login">

Check out this demo for reference.

Answer №3

I made a change by removing the following code:

❌
<button type="button" @click="login" @keyup.enter="login" > Login</button>

Instead, I replaced it with this code and it worked as expected:

<input type="submit" value="login" @keyup.enter="login()">

Thank you for your help and responses, I truly appreciate it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NPM is searching for the package.json file within the user's directory

After completing my test suite, I encountered warnings when adding the test file to the npm scripts in the local package.json. The issue was that the package.json could not be located in the user directory. npm ERR! path C:\Users\chris\pack ...

Employing the join() method on an array that is nested within object entries retrieved from a vuex

I am struggling to format my vuex getter to return errors in a specific structure. Currently, my errors object looks like this: errors: { email: ['error message.'] email_confirm: ['error message.', 'another error message.&apo ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

Is Selenium designed to work with standalone browsers (using webdrivers) or with browsers that are already installed on the operating system?

I am a newcomer to Cross Browser Testing and have just begun exploring Selenium. However, I am having trouble finding the answers to the following questions on the official site. It would be greatly appreciated if someone could help clarify them for me. ...

What could be causing the Autocomplete feature to display as undefined?

I'm encountering an issue where the Autocomplete box displays "undefined" even though it returns the expected results. How can I resolve this problem? import { Drawer, List, Typography, Switch, ListItem, ListItemText, ListItemSecondaryAction, TextFiel ...

Button ng-click with identical function parameters

I am facing an issue with two buttons that have the same ng-click but different parameters. <label class="item item-input"> <button ng-click="takePicture(true)">Save Settings</button> <button ng-click="takePicture(false)">Choos ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Node JS encountered an unhandled promise rejection warning, while React received a preflight response

Working with React JS: Take a look at the code snippet below: ....some code...... verifyTokenResults = await axios.post('http://localhost:5000/otp/token/verify', {accessToken: authToken}) Here, I am sending a token from a React component to a ...

The date range picker displays the previous arrow but not the next arrow

I am currently using the DateRangePicker tool and for some reason, I am not seeing the arrow that should appear on the right side. I have double-checked my configuration but can't seem to figure out what is causing this issue. In the image attached, ...

Is it necessary to confirm the validity of url.format(urlObject)?

I have been exploring the NodeJS URL API and am particularly interested in the url.format(urlObject) method. My goal is to develop a function that first validates the urlObject before using the format function, and throws a TypeError if any of the key/valu ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

Automatically conceal a div or flash message after a short period of time by utilizing CSS3 in a React

I am relatively new to the React environment and recently created a basic component for a bookmarking feature. Essentially, when the favourite icon is clicked, an ajax call is sent > a record is created in the database > on ajax success, a flash me ...

Issue: The registration token(s) provided for the sendToDevice() function are not valid

Currently, I am working on my final project where I am attempting to send notifications using Firebase Cloud Function when onUpdate is triggered. However, I encountered an error during the process. Despite following tutorials on YouTube and various website ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

Developing a MySQL Community Server-backed RESTful Web Service with the power of jQuery AJAX

I am currently in the process of developing a RESTful Web Service using MySQL Community Server alongside jQuery AJAX Unfortunately, my usage of jQuery AJAX is not functioning as expected. When attempting to add, delete, update a product, or retrieve all p ...

The message of error is undetermined

Can someone help me with using the errorMessage object from routes in a partial? I have attempted to implement it as shown below: Route:- const express = require("express"); const router = express.Router(); const Character = require("../models/character" ...

Navigating to the parent node in a treeview within the wijmo flex grid: a step-by-step guide

Utilizing the wijmo flex grid, I've successfully created a tree view for my data. I can determine if a specific node has children and its level, but I'm struggling to navigate to the parent node from a given one. Additionally, I am able to retrie ...

Transforming my asynchronous code into a synchronous flow using setTimeout. Should I consider implementing promises?

I have a project in which I am creating a data scraper for a specific website. To ensure that I make a request only every 10 seconds, I have set up a setTimeout loop. This loop takes a URL as a parameter from an array of URLs that I manually input. In the ...