Ensuring form input validity in real-time using jQuery's keyup event

I've been working on a form where the user can fill in an input and press enter to move to the next field.

Although I have managed to get the functionality to show the next div, I am facing issues with validation...

// Moving to next div on Enter key...
$(window).load(function(){
$('footer .active input').on("keyup", function(e) {
    e.preventDefault();
    
    if (e.keyCode === 13) {
        if( $('footer .active input').val().length === 0 ){
            alert('NO!');
        } else {
            var $activeElement = $("footer .active");
            $( "footer .active" ).next().addClass( "active" ).removeClass('inactive');
            $activeElement.removeClass("active").addClass('inactive');
        }
    }
});
});
form {
    overflow: hidden;
    width:100%; min-height:200px;
    position:relative;
}
div.inactive {
    position: absolute;
    display: none;
    width:100%;
    border-bottom:1px solid rgba(255,255,255,0.3);
}
input { 
    padding:2.5rem 0;
    font-size:4rem;
    font-weight:200;
    width:80%;
}
.active {
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer>
    <form action="">
        <div class="input active">
            <input type="text" placeholder="Who are you?" />
        </div>
        <div class="input inactive">
            <input type="text" placeholder="What is your Email?" />
        </div>
        <div class="enter-btn"></div>
    </form>
</footer>

Answer №1

If you want to trigger an event on keyup for the input field inside a footer that is currently active, use

$(document).on("keyup",'footer .active input', function(e) {})

// Form on enter next div...
$(document).on("keyup", 'footer .active input', function(e) {
  if (e.keyCode == 13) {
    if ($('footer .active input').val() == '') {
      alert('NO!');
    } else {
      var $activeElement = $("footer .active");
      $("footer .active").next().addClass("active");
      $activeElement.removeClass("active");
    }
  }
});
form {
  overflow: hidden;
  width: 100%;
  min-height: 200px;
  position: relative;
}
form div.input {
  position: absolute;
  display: none;
  width: 100%;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
form div.input input {
  padding: 2.5rem 0;
  font-size: 4rem;
  font-weight: 200;
  width: 80%;
}
form div.input.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer>
  <form action="">
    <div class="input active">
      <input type="text" placeholder="Who are you?" />
    </div>
    <div class="input">
      <input type="text" placeholder="What is your Email?" />
    </div>
    <div class="enter-btn"></div>
  </form>
</footer>

Answer №2

Revise the following line:

if( $('footer .active input').length === '' ){

to

if( $('footer .active input').val() == '' ){

and give it another shot.

Important: Make sure to validate the input value.

Check out the Updated Fiddle

Answer №3

Avoid using "length === '' " The length property returns an integer, so it cannot be compared to an empty string (which is of type string). Instead, try the following:

if( $('footer .active input').val().length <= 0 ){

Answer №4

Here is a line of code that needs correction:

if( $('footer .active input').length === ''

There are three mistakes in this comparison:

  1. You are using a strict comparison operator to compare a number value with a string value.
  2. The length should be expected to be 0, not an empty string.
  3. You are comparing the property length of a jQuery object, which represents the number of matching DOM elements for your selector.

To fix the line, you can use either of the following options:

if($('footer .active input').val().length == 0)

or

if($('footer .active input').val() == '')

Note: consider using e.target instead of querying the same element multiple times.

Answer №5

$('footer .active input').length reveals the quantity of elements that meet the specified criteria. To retrieve the value of the input, utilize .val() instead:

// Proceed to next div upon form submission...
$('footer .active input').on("keyup", function(e) {
  if (e.keyCode == 13) {
    if ($('footer .active input').val() == '') {
      alert('NO!');
    } else {
      var $activeElement = $("footer .active");
      $("footer .active").next().addClass("active");
      $activeElement.removeClass("active");
    }
  }
});

https://jsfiddle.net/g51xbfy6/2/

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

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

Simplify your code with promises in JavaScript

Running on an API with node v6.3.0, I have the following code that executes two separate promises based on a conditional check for a parameter in a POST request. if (paramExists) { // query database with this condition User.filter(/* utilize param ...

What could be the reason for the misalignment between md-menu and md-button when ng-href is included in the button?

Check out the demo by clicking here: http://codepen.io/audiodude/pen/vLyNvw The main distinction between the top and bottom sections lies in the fact that the top section utilizes an md-button with an ng-href attribute, which Angular Material compiles int ...

Encountered an error: Trying to access 'location' property from undefined in express app

Encountered Issue : I am facing an error that is hindering me from fetching data from the HTML form. Every time I input values into the form and click the button to send the data to an API for saving it in the database, this error pops up: Cannot read pro ...

When attempting to incorporate the "active" class into a Bootstrap 4 carousel using jQuery, issues arise specifically when retrieving data from a MongoDB database

I'm working on a carousel feature where I need to load images from my MongoDB database. However, the issue I'm facing is that even though I've tried adding the active class to the first item, the carousel doesn't transition to display t ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

Creating links within a single image in HTML?

Is there a way to hyperlink different parts of a single image to various webpages using JavaScript coordinates or any other method? ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

What is the best way to retrieve the value of a div using AutoIt?

For this particular scenario, my objective is to extract a specific value from the last div element in the following list: <div id="past"> <div class="ball ball-8" data-rollid="242539">11</div> <div class="ball ball-8" data-ro ...

Arrange the array so that the item is placed at the beginning while maintaining the original order

Currently facing a roadblock with this particular issue. I am attempting to create a function that accepts an index as input and rearranges the element at that index in an array to be placed at the beginning, while keeping the order of the other elements a ...

Tips for displaying a PNG image correctly within the navbar

I'm facing an issue with adding a logo to the navigation bar, as the logo I want to use doesn't display correctly. Even after trying to adjust the width and height, it continues to stretch inappropriately and the text on the image remains unread ...

What is the reason behind receiving the error "PHP Warning: Trying to access property "nodeType" on null" when using this PHP AJAX search function?

I am working on developing a real-time search feature inspired by an example from w3schools, which can be found at this link: https://www.w3schools.com/php/php_ajax_livesearch.asp. My task involves searching through an xml file containing 1000 different it ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...

I'm looking to optimize my paragraph for small screens by incorporating a Google AdSense banner

I need help adjusting my content with a Google banner for small screens. Here is an example image: Example Image Within the parent div with the class name parent-content, there is a banner div named ad3. Below is the code I have written for screens with ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

Tips for utilizing @htmlattributes when configuring a datepicker:

Hello, I am attempting to change a simple input field into a date form. I have tried using the DateTime property with @Html.TextBoxFor(model => model.dateFin, new { type = "date" }) but it was not successful. As a result, I am resorting to using a simpl ...

Identifying identical web elements using Python Selenium through related attributes

Having attempted to solve this problem for the third time, I find myself unable to come to a final solution on my own. I would greatly appreciate it if someone could offer their insights on the issue at hand. Let's consider the following HTML structu ...

Is there a way to ensure that an AJAX request to a PHP file is synchronized with submitting form data to that same file?

My issue is that update.php is only able to retrieve the posted form data (post_edit). The variables sent earlier through AJAX are not being passed through. Notice: Undefined index: id_to_edit in ...\update.php on line 5 Notice: Undefined index: col ...

Eliminating clutter in bespoke event handlers - eliminating the necessity for the 'event' parameter

I have a project where I am creating objects that will trigger custom events, and I am using jQuery's bind and trigger functions to handle this task. Here is an example of how I am implementing it: function MyObject() { var _this = this; th ...