Reasons why `return()` and `onsubmit()` may fail when implementing a login form that redirects to a welcome page in HTML

Encountered an issue while developing a login form from HTML, CSS, and JS where the return statement was not functioning properly.

Please provide code for implementing HTML embedded JavaScript.

<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
    
</head>
<body>
<div class="loginbox">
<img src="C:\Users\Hp\Pictures\Camera Roll\avatar2.png" class="avatar">
<h1>Login Here</h1><br>
<form action="loginbox.html" method="post" onsubmit="return validate()">
<div>
<p>user name</p>
<input type="text" name="" placeholder="Enter User name" id="user name">
</div><br>
<div>
<p>password</p>
<input type="password" name="" placeholder="Enter password" id="password">
</div><br>
            <input type="submit" name="" value="login"><br>
<a href="#">Lost your pasword??</a><br>
<a href="#">don't have an account??</a>
</form>
</div>
    
    <script type="text/javascript">
    var attempt = 3;
function validate()
{
        var user name= document.getElementById("user name").value;
        var password= document.getElementById("password").Value;

if(user name.value=="dr" && password.value=="8428")
{      
             
            return true;
        }
else{
attempt --;// Decrementing by one.
            alert("You have left "+attempt+" attempt;");
            // Disabling fields after 3 attempts.
            if( attempt == 0){
            document.getElementById("username").disabled = true;
            document.getElementById("password").disabled = true;
            document.getElementById("submit").disabled = true;
            return false;
}
}
</script>
   
</body>
</html>

Despite using the return false statement to prevent entry into the welcome page, the code is still progressing to the next page.

Experimented with

onsubmit="return false; validate();"
which resulted in the entire block halting without proceeding to the welcome page.

Answer №1

It seems like there are some errors in your code that need to be addressed. Firstly, using spaces in the id attribute is incorrect and should be avoided. Additionally, the submit button is missing the id="submit" attribute, which is causing issues with executing JavaScript.

document.getElementById("submit").disabled = true;

The above line of code is unable to execute because the submit button lacks an ID element. Below is the corrected version of your code:

<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
    <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>
    <div class="loginbox">
    <img src="C:\Users\Hp\Pictures\Camera Roll\avatar2.png" class="avatar">
    <h1>Login Here</h1><br>
        <form action="loginbox.html" method="post" onsubmit="return validate()">
            <div>
            <p>user name</p>
            <input type="text" name="" placeholder="Enter User name" id="username">
            </div><br>
            <div>
            <p>password</p>
            <input type="password" name="" placeholder="Enter password" id="password">
            </div><br>
            <input type="submit" name="" value="login" id="submit"><br>
            <a href="#">Lost your pasword??</a><br>
            <a href="#">don't have an account??</a>
        </form>
    </div>

    <script type="text/javascript">
    var attempt = 3;
    function validate()
    {
        var username= document.getElementById("username").value;
        var password= document.getElementById("password").Value;

        if(username == "dr" && password == "8428")
        {      

            return true;
        }
        else{
            attempt --; // Decrementing by one.
            alert("You have left "+attempt+" attempts.");
            // Disabling fields after 3 attempts.
            if( attempt == 0){
            document.getElementById("username").disabled = true;
            document.getElementById("password").disabled = true;
            document.getElementById("submit").disabled = true;
            return false;
        }
    }
    </script>

</body>
</html>

Answer №2

The issue arose from the absence of an id in the submit section; it is necessary to declare an id for the input with type submit. Additionally, there was a flaw in the logic when validating the form as the return statement was missing in the else part if the attempt was not equal to zero.

<!DOCTYPE html>
<html>

<head>
  <title>LOGIN FORM</title>
  <link rel="stylesheet" type="text/css" href="style.css">
 <script type="text/javascript">
var attempt =3;
function validateForm() {

      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;

      if (username == "dr" && password == "8428") {

        return true;
      } else {
         attempt--;// Decrementing by one.
        alert("You have left " + attempt + " attempt!");
        // Disabling fields after 3 attempts.
        if (attempt == 0) {
        
          document.getElementById("username").disabled = true;
          document.getElementById("password").disabled = true;
          document.getElementById("submit").disabled = true;
         return false;
        }
        
        return false;
      }
      }
  </script>
</head>

<body>
  <div class="loginbox">
    
    <h1>Login Here</h1><br>
    <form action="/loginbox.html" name="myForm"  onsubmit="return validateForm()">
      <div>
        <p>user name</p>
        <input type="text" name="userName" placeholder="Enter User name" id="username">
      </div><br>
      <div>
        <p>password</p>
        <input type="password" name="password" placeholder="Enter password" id="password">
      </div><br>
      <input type="submit" id="submit" value="login"><br>
      <a href="#">Lost your pasword??</a><br>
      <a href="#">don't have an account??</a>
    </form>
  </div>

 

</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

Creating a clickable table row in bootstrap with optimal effectiveness

Is it better to implement a clickable row using jquery or pure JS? Consider server and client efficiency Ensure compatibility with various browsers The jquery option: // my tr (row) class <tr class='clickable-row' data-href='url:www.g ...

When encountering duplicates within an array, I must ensure that the complete structure of the array is preserved and stored in MongoDB

I have encountered a situation where I am looping through an array and need to save the data in a MongoDB database. However, I need to avoid duplicating the array's indexes. I was thinking of using a filter to achieve this, but I'm concerned abou ...

jQuery scroll to id is a function that allows you to smoothly

I have been creating onepage websites for quite some time now, and one issue that always bothers me is the repetitive navigation functions I need to write for each button and id. Here's what it typically looks like: $('#homeB').click(funct ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

Sending array data from the client-side JavaScript to the Spring MVC controller via AJAX

Is there a way to send an array from JavaScript in a web browser to a Spring MVC controller using AJAX? Here's the JavaScript code I have: var a = []; a[0] = 1; a[1] = 2; a[2] = 3; // Is it possible to send multiple arrays as well? $.ajax({ typ ...

CSS - Align two divs inline, positioning the first div to the left and the second div to the center

We are looking to create two inline divs where the first div is aligned to the left and the second div is centered on the same line. <div style="margin-top:200px;"> <div align="left" style="display:inline;"> <label> ...

Learn how to effectively manage NodeJS in cluster mode by monitoring the CPU and memory usage of each worker

I have a Node Application running in cluster mode on an AWS ec2 instance that has 4 CPUs and 7.5 GB of RAM. I am looking to monitor the CPU and memory usage of my application, specifically for each of the 4 worker processes. Are there any tools available ...

Differences between Cypress and JQuery objects, and the significance of the cy.wrap function

Currently diving into cypress and experimenting with various testing methods. If anyone could lend me a hand with the following inquiries: 1. I've come to understand that most cypress objects utilize jQuery objects for DOM operations, but what sets t ...

Calculate the combined sum of values within dynamic inputs that share a common class, and automatically update the sum whenever input values are altered or new rows are added or removed dynamically

$("#add-btn").click(function() { $("#dynamic").append('<tr>' + '<td class="td">' + '<input type="number" name="Debit" class="form-control Debit"/>' + '</td>' + '<td c ...

Displayed unfamiliar Obj characters on Google Chrome

Hey there, I'm new to Vue JS and Vuetify and could really use some help! I've been trying to display some HTML content from my data using v-html in Vue JS, but for some reason, strange OBJ symbols keep showing up. Here is a screenshot of what I ...

The ng-scope class in AngularJS is failing to be applied

While exploring the Angular Tutorials, I noticed an interesting detail in their example where the ng-scope CSS class is added to each element with a directive. If you want to check out the tutorial for yourself, here's the link: Angular Tutorial on S ...

Host your own website online using your personal computer

So I have created a simple HTML page that I want to publish on the Internet using my PC. This is just for testing purposes, so I don't require a static IP address or high uptimes. First, I installed Tomcat Apache and placed my WAR file in the webapps ...

Issues arise when attempting to use two HTTP get requests in a single AngularJS controller

Having two http GET requests in one controller, causing intermittent issues where only one of the GET requests works or sometimes none of them are shown. Any suggestions? }).controller("nextSidorAdminCtrl", function($scope,$rootScope,$http,$location,$s ...

The Vue JS Option element requires the "selected" attribute to be utilized as a property instead

I'm attempting to automatically have an option selected if the "selected" property is present on the option object. Here is my code snippet: <template> <select v-model="model" :placeholder="placeholder"> <option v-for="opt ...

Guide on displaying gallery images when clicking on a specific class

I am in the process of developing a gallery tab for a website, initially displaying three thumbnails. The goal is to reveal the remaining thumbnails when a class named show-all is clicked. I have successfully animated the gallery's height to show the ...

Express Server React 403 Forbidden Error

Issue: When attempting to make a post request using the AXIOS library in React, I am receiving a 403 (Forbidden) error for http://localhost:5004/api/auth/login. Despite having installed cors on Express, the console continues to display the 403 error. My c ...

Convert numeric month to its 3-letter abbreviation

Receiving the date time value from the server and storing it in a variable named a1: let a1 = (new Date(estimatedServerTimeMs)); console.log of a1 Sun Apr 05 2020 11:36:56 GMT+0530 (India Standard Time) The date is converted to a simpler format such as ...

Increase the spacing between the column label and the x-axis label in a c3 chart

Take a look at the chart below, I'm attempting to create some additional spacing between the column labels and the x-axis label. https://i.sstatic.net/R7zqN.png I experimented with adding this CSS style: text.c3-axis-x-label { margin-top: 10 ...

As I iterate through a MySQL array, JavaScript is able to manipulate the initial displayed data

I'm struggling to achieve the desired outcome with my code. It seems that when I iterate through an array of data, JavaScript only works on the first echoed data. Here is a snippet of the code: <?php $ids = array(); ...

The boolean value remains constant when using useState

An Alert module pops up when incorrect credentials are entered by the user. It includes a close button designed to hide the alert. The alert function operates correctly on the first instance, displaying a boolean value of true upon activation and switching ...