Suggestions for showing an error message when a field is empty and the user moves on to the next one

When a user begins typing a password without entering their email address first, immediately display the message - “Please Enter Your Email Address First”. My project utilizes bootstrap4 and jQuery/Javascript. I need the cursor to move to the field where an error is detected. Additionally, when all validations are met, how can I redirect to another page upon clicking the Submit Button? I've attempted using anchor tags in HTML for redirection upon button click, but it redirects to the link instead of validating. I've also tried using the window.location method with no response.

<!DOCTYPE html>
<html>

<head>
  <title>Three Forms</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>;

<body style="background-color: grey">
  <div class="container" style="background-color: green;padding-bottom: 2%;">
    <div style="background-color: black;">
      <h2><b>Forms</b></h2>
    </div>
    <div class="row" style="margin-top: 3%;">
      <div class="col-xs-12 col-sm-6 col-md-3" style="background-color: white;padding: 0px;margin-left: 4%;margin-right: 3%;margin-bottom: 3%;">
        <form class="form-A" id="form-A">
          <div style="background: linear-gradient(to top left, #ff9999 0%, #ff9966 35%); height: 100px; text-align : center; color:white;">
            <h3><b>Log In</b></h3>
    
          </div>
          <div style="padding: 4%;">

            <div class="form-sm">
              <!-- Input fields removed for brevity -->
            </div>
          
          </div>
        </form>
      </div>


      <div class="col-xs-12 col-sm-6 col-md-3" style="background-color: white;padding: 0px;margin-left: 4%;margin-right: 3%;margin-bottom: 3%;">
        <form id="form-B" style="padding-left: 4%;padding-right: 3%;margin-left:-4%;margin-right:-3%;">
          <h3 style="color:#cc00cc;text-align : center;"><b>Sign Up</b></h3>
          <div class="md-form form-sm" style="padding: 3%;">
            <!-- Input fields removed for brevity -->
          </div>
          
        </form>
      </div>

      <div class="col-xs-12 col-sm-6 col-md-3" style="background-color:white;margin-left: 4%;margin-right:3%;padding:top:0.5%;margin-bottom: 3%;">
        <form id="form-C">
          <h3 style="text-align : center;"><b>Sign In </b></h3>
          <div class="md-form form-sm" style="padding-top:1%;">
            
          </div>
         
        </form>
      </div>
    </div>
   </div>
   
    <script>
      // Form validation scripts removed for brevity 
     
    </script>

</body>
 
</html>
;

Answer №1

If you're looking for an effortless solution, I've crafted a straightforward form that gets the job done.

Utilizing the Element.scrollTo() method, I guide the user to the required field with ease.

let checkFill = el => {
  let siblings = [...el.parentNode.children];
  let bool = true;
  
  if(siblings.indexOf(el) !== 0) {
    for(let s of siblings) {
      if(s !== el) {
        if(s.value.length === 0) {
          alert('Fill out the previous fields first!');
          window.scrollTo(0, s.offsetTop);
          s.focus();
          bool = false;
          break;
        }
      } else break;
    }
  }
  
  return bool;
};

let redirect = bool => {
  if(bool) {
    window.location.href = 'https://stackoverflow.com/';
    console.log(window.location.href);
  }
};
input {
  display: block;
  height: 40px;
  width: 75vw;
  margin: 20vh auto;
  font-size: 20pt;
}

button {
  height: 80px;
  width: 400px;
  margin: 10vh;
  font-size: 20pt;
}
<form>
  <input type='email' onFocus='checkFill(this);' required/>
  <input type='password' onFocus='checkFill(this);' required/>
  <input type='number' onFocus='checkFill(this);' required/>
  <button id='btn' onClick='redirect(checkFill(this));'>Log In</button>
</form>

Answer №2

Review the snippet below where validations have been added to input fields when focused on. The validation works correctly for form1. It was necessary to remove the focus in the validation function to prevent it from getting stuck in a loop. I recommend creating separate validations for input focus and form submission.

<!DOCTYPE html>
<html>

<head>
  <title>Three Forms</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>;

<body style="background-color: grey">
  <div class="container" style="background-color: green; padding-bottom: 2%">
    <div style="background-color: black;">
      <h2><b>Forms</b></h2>
    </div>
    <div class="row" style="margin-top:3%">
      <div class="col-xs-12 col-sm-6 col-md-3" style="background-color: white; padding:0px;margin-left: 4%; margin-right: 3%; margin-bottom: 3%;">
        <form class="form-A" id="form-A">
          <div style="background: linear-gradient(to top left, #ff9999 0%, #ff9966 35%); height: 100px; text-align: center; color:white;">
            <h3><b>Log In</b></h3>
            <a href="https://www.facebook.com"><i class="fa fa-facebook" style="color:white;"></i></a>
            <a href="https://twitter.com"><i class="fa fa-twitter" style="color:white;"></i></a>
            <a href="https://plus.google.com"><i class="fa fa-google-plus" style="color:white;"></i></a>
          </div>];
          <div style="padding: 4%">

            <div class="form-sm">
              <input type="Email" id="email1" class="form-control form-control-sm" placeholder="Your Email">
            </div>
            <div class="mb-2"></div>
            <div class="form-sm">
              <input onfocus="form1validations()" type="Password" id="password1" class="form-control form-control-sm" placeholder="Your Password">
            </div>
            <div class="text-right mt-4">
              <a class="btn btn-link" href="https://www.google.com" style="color:grey;font-size:normal;">Forgot Password?</a>
            </div>
            <div class="text-left mt-4" style="font-size:8px; font-weight: normal;">
              <button class="btn btn-primary" id="login" style="Background-color:grey; border-radius:25px;" onclick="return form1validations() ">
Log In<i class="fa fa-paper-plane-o ml-1"></i></button> &nbsp;
              <span style="color:grey;">Don't have an account?</span>
              <a class="btn btn-link" href="Sign Up" style="text-align: right; color:black; font-size:10px;">Sign up?</a>
            </div>
            <div class="pb-4"></div>
          </div>
        </form>
      </div>


... (remaining code truncated for brevity)

    </div>
    <div class="mb-3"></div>

    <script>
      // JavaScript validation functions here
    </script>

</body>

</html>

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

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

Expanding a div container to accommodate its inner divs using CSS

I have a div containing three inner divs. ONE - I am div TWO - I am div THREE - I am div When viewed on mobile, only two divs can fit in a row horizontally. I want the third div to move down. Like this: ONE - I am div TWO - I am div THREE - ...

Checking the status of a Promise within Promise.finally() without needing to await it in a live environment

In my development code, I am utilizing Promise.prototype.finally() (or try-catch-finally in an async function) to run additional code without altering the resolution or rejection status of the current promise. However, when it comes to testing with Jest, ...

Having trouble with transferring image blob to AWS S3 with node.js & angular

I'm having trouble uploading my images to AWS S3 { [InvalidParameterType: Expected params.Body to be a string, Buffer, Stream, Blob, or typed array object] message: 'Expected params.Body to be a string, Buffer, Stream, Blob, or typed arr ...

What can be done to prevent an image from vanishing along with its containing div?

I recently created a website/application where users can interact with elements by dragging them around the page. However, I encountered an issue where one element disappears when dragged outside of its original container. How can I prevent this from happe ...

Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide TEST: import { render, screen } from 'test-util'; import { Sideb ...

The connection to Cordova.js is established, but the deviceready event is not

I've included cordova.js in my project, called app.initialize();, but for some reason deviceready event is not being triggered. Any ideas on what might be causing this issue? Here's the JavaScript code: var app = { initialize: function() { ...

Discover a personalized message and alter its hue using JavaScript and CSS styling

I've hit a roadblock while creating my website with WordPress and a custom theme. Although I can easily inject custom Js or CSS, I need advice on how to achieve the following: How can I locate the symbol ★ within the content and change its color? ...

Tips for Wrapping Page Layouts and Routes in Angular 4

As I work with my regular angular 4 app, I often find myself using Router, ActivatedRoute.params.subscribe, [routerLink], and other tools to navigate between pages and interpret URLs. This results in a multitude of "magic strings" scattered throughout var ...

Is it possible for mesh1 and mesh2 to automatically adjust their positions based on scale?

I have a goal to connect the right side of mesh 1 with the left side of mesh 2. Whenever I scale mesh 1, it requires me to readjust the position of mesh 2 in order to maintain the original distance between them. Let's try scaling mesh 1 by setting z ...

Increase the size of the logo in the navbar without causing any distortion to the other elements

I am currently facing an issue with my logo placement in the header section of my website. The header consists of a background image with a navbar and logo embedded within it. HTML <div class="header"> <div class="container"> < ...

How to execute a function *after* another function has finished running in Javascript upon page load?

I am currently using scrollsaver.js to maintain scroll positions of elements after postback. However, I have encountered difficulties in resetting the scroll position when needed. Specifically, when paging through a list, I want the scroll position to res ...

Updating events instantly with a single click in Angular 6: A step-by-step guide

Hello there, I am currently diving into learning Angular 6 and I have encountered a query. I want to achieve a functionality where upon clicking a button, the text on the button changes as well as the corresponding event that triggers when the button is cl ...

Implementing Dynamic Script Injection in Angular Controllers for Enhanced HTML Functionality

I'm a total beginner when it comes to Angular and frontend development, so please bear with me if my question seems basic: In my controller, I have the following code where I am populating the $window.user data that is being used in the script [2] ad ...

React counter variable failing to increment

I have 6 cubes displayed on the screen along with a counter. Whenever a cube is clicked, its background color changes to red and the counter increments by one. However, I'm facing an issue where the counter remains at 1 even after clicking on multiple ...

What is the method for retrieving the XMLHttpRequest errors registered with addEventListener?

I am struggling to find a solution. https://i.stack.imgur.com/bRJho.gif ...

limitation in bootstrap ensures that only one collapse element is open at any

Hey, can someone help me fix this code? I'm trying to make it so that only one element opens at a time, but I can't seem to figure out how. Right now, if I click on two elements, they both open and the other one doesn't close. This is what ...

Cypress: harnessing the power of regular expressions within jQuery selectors for the ":contains()" method

Trying to use Cypress along with a regular expression to target an element that includes specific text. The following get() function successfully works: cy.get('[data-cy=tile]').contains(new RegExp(myVar)) However, the following command does no ...

Incorporating AngularJS into your current JavaScript code base

We have a JavaScipt project underway that could greatly benefit from incorporating AngularJS. However, due to the size of the project, completely rewriting it in Angular is not feasible. Does anyone have any suggestions or tips on how to integrate Angula ...

A guide on updating div IDs using jQuery sortable when an element is moved by the user

My goal is to use jQuery sortable to allow users to rearrange elements on a page by dragging and dropping them. Each div element has a unique ID, and when the user swaps elements, I want to update the IDs accordingly and alert the new order so it can be sa ...