Unable to move to a different HTML page following validation with JavaScript

Recently, I completed a HTML page that consists of two separate sections - one for logging in and the other to display after a successful login. In order to ensure proper validation on the login.html page, I implemented the following:

However, when attempting to redirect to the second HTML page (landing.html) upon successful validation of the input fields, I encountered an issue where instead of loading the landing page, the input fields would clear and the data would display in the URL.

I am seeking guidance on how to successfully redirect to the landing.html page located within the same folder after validating the input fields on the login.html page.

function validate(event) {
  event.preventDefault();
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  if (username == "username" && password == "user123") {
    window.location.href = "landing.html";
  } else {
    alert("Invalid credentials");
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<div class="container">
  <div class="box">
    <h1>Login</h1>
    <form class="form">
      <label>Username</label>
      <div>
        <i class="fa fa-user"></i>
        <input type="text" name="username" id="username" placeholder="Enter Username">
      </div>
      <label>Password</label>
      <div>
        <i class="fa fa-lock"></i>
        <input type="password" name="password" id="password" placeholder="Enter Password">
      </div>
      <a href="#" class="forgot">Forgot Password?</a>
      <input type="submit" value="Login" onclick="validate()">
    </form>
  </div>
</div>

Answer №1

Event.preventDefault can only be used if the event listener is assigned to the button or form event directly

For forms, it's best to utilize the submit event!

Have you considered changing the form action instead?

It's strongly advised against having user id and password in the HTML file

window.addEventListener("DOMContentLoaded", () => {
  document.querySelector(".form").addEventListener("submit", function(e) {
    const username = this.username.value;
    const password = this.password.value;
    if (username === "username" && password === "user123") {
      this.action = "landing.html";
    } else {
      e.preventDefault(); // should go here
      alert("Invalid credentials");
    }
  })
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<div class="container">
  <div class="box">
    <h1>Login</h1>
    <form class="form">
      <label>Username</label>
      <div>
        <i class="fa fa-user"></i>
        <input type="text" name="username" id="username" placeholder="Enter Username">
      </div>
      <label>Password</label>
      <div>
        <i class="fa fa-lock"></i>
        <input type="password" name="password" id="password" placeholder="Enter Password">
      </div>
      <a href="#" class="forgot">Forgot Password?</a>
      <input type="submit" value="Login">
    </form>
  </div>
</div>

Answer №2

You have incorrectly identified the issue at hand.

There is no concept of "after validation."

The problem lies in your implementation of the onclick="validate()" function, where you are passing undefined to the event argument within function validate(event) {. Subsequently, calling event.preventDefault(); causes an error as undefined is not treated as an Event object, leading to a function interruption.


To address this, bind your event handlers using addEventListener, which overcomes the limitations associated with onclick attributes and ensures proper handling of event objects within the function.

Furthermore, it is advisable to listen for submit events on the form rather than relying solely on click events for the submit button.

document.querySelector('form').addEventListener('submit', validate);

Note: Your current approach poses significant security risks. It is crucial to withhold sensitive data such as URLs until after the process of Authentication (AuthN) has been completed on the server-side. Exposing such information prematurely through client-side scripts leaves it vulnerable to potential unauthorized access by users viewing the page source code.

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

Having trouble getting a Mocha test to display two decimal places in Javascript? Both Big and Decimal libraries are causing issues

After encountering an error with the Big library, I decided to switch to Decimal. First, I ran npm install Decimal Then, I added the following code: const Decimal = require('decimal'); Even after following the examples, my comparison returned { ...

Is it possible to merge upload file and text input code using AJAX?

For my form submissions using jQuery and Ajax, I'm trying to figure out how to send both data and files together. Currently, I have the following code: $("#save-sm").bind("click", function(event) { var url = "sm.input.php"; var v_name_sm = $(&ap ...

Tips for creating a global variable by combining form input and an API request in React

Currently, I am in the process of constructing a simple login page for my React application. The way it works is that when a user submits a form to log in, if the entered username and password match what's stored in the database, an object is created ...

Button linked to jQuery File Upload

Currently, I am exploring the functionalities of the jQuery File Upload Plugin here I am looking to achieve a behavior similar to the homepage that loads - allowing the selection of multiple files. Once selected, I do not require the option to upload file ...

Attempting to decode the warnings that appear while utilizing babel for react.js

Recently, I created a basic React rendering function that displays the word "hello" within a div element with the id of "react-container". However, I have been encountering warning messages in the console such as: unreachable code after return statement ...

What is the best way to use PHP to show a PDF in a new browser tab instead of downloading the file?

I am working on updating the code to change the action of opening a PDF file in a new browsing tab instead of downloading it locally. Can anyone provide guidance on how to make this update? public function openFileInNewTab($fileID) { $this->load-& ...

What are some methods to secure my API keys within my React application?

What steps can I take to secure my api keys in my react application? Should I incorporate something with express? My goal is to avoid creating any server-side components to handle the API calls. Currently, my backend is managed by firebase but I also uti ...

What are the steps to create a class diagram for a NodeJS application?

For my final year project, I am looking to develop an application using Node API. As we delve into drawing the class diagram, it occurs to me that unlike Java or C#, Node JS does not have a built-in class concept. What would be the most effective approac ...

Mongoose is having trouble identifying the 2dsphere index I created

I am currently attempting to add a 2dSphere index for the field startLocation within the tourSchema. This is how it is defined: startLocation: { type: { type: String, default: 'Point', enum: ['Point'] ...

Sinon.js: spying on an empty callback

Currently, I am experimenting with callback functions using sinon.js handleLoginActions = function (callback) { ... if (callback) { callback() } .. } var loginCallbackStub = stub(); handleLoginActions(loginCallbackStub); expect(lo ...

Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format? For example, how can we convert the array ["a.b.c.d", "a.c.e.f", "a.b.c.g"] into the following JSON structure: items:{ text: "a", items:[ { ...

Using JavaScript, import the variable module object from a specific module

Is there a way to import a module object from a module if I am unsure of the specific objects I will need beforehand? How can I utilize a variable in place of fixed module names? import { dynamicVariable } from './module' The variable represents ...

Resizing an iframe dynamically based on the content of the URL without displaying a scroll bar using JavaScript

Within my application, there is a select drop-down menu that contains URLs. When a user selects a URL from the drop-down menu, I want to load that URL in an iframe with the appropriate content size. I am looking for a way to increase the height of the if ...

Tips for using the useState hook to modify an array by its index?

I am working on a select component that needs to update values in an array of objects based on the index. Utilizing the hook as follows: const [areas, setAreas] = useState(product.areas); This is how the "areas" array looks: [ 0: {de: "Getraenke", en: ...

The integration of Boostrap with Angular's ng-include directive

Let's discuss a scenario I've encountered: in my main index.html page, I have the following code: <aside> <ul class="nav nav-pills nav-stack" id="myAffix"> <li>...</li> <li>...</li> ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Replacing all backslashes with forward slashes cannot be done using just one quotation mark; the process involves changing each ""

Struggling to switch all backward slashes with forward slashes " from \ to / . Experimented with numerous possibilities but without success. var a = 'images\1572714983295\10423479\401891269961412\82824649\n.jpg'; ...

Located at the lower section of the parent container

In my flex container, I have two boxes arranged side by side (collapsing into one column on smaller screens). I've ensured that these boxes have the same height when displayed together, as shown in the image below: https://i.sstatic.net/ZjsfW.png No ...

What could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...

Placing an item from a "stack" onto a separate line on smaller screens

My goal in Bootstrap is to achieve the design shown in this image: https://i.stack.imgur.com/9Eoen.png The first layout can be achieved by placing B and C within the same div container. The second layout can be accomplished by defining C on a new row ind ...