Issues with the functionality of the login page's HTML and JavaScript

Recently, I attempted to create a login page with the following code:

const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-form-submit");
const loginErrorMsg = document.getElementById("login-error-msg");

function validate_login() {
loginButton.addEventListener("click", (e) => {
    e.preventDefault();
    const username = loginForm.username.value;
    const password = loginForm.password.value;

    if (username === "user" && password === "web_dev") {
        window.location.href="https://airtable.com"
    } 
    else {
        loginErrorMsg.style.opacity = 1;
    }
})}
html {
    height: 100%;
  }
  
body {
  height: 100%;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  display: grid;
  justify-items: center;
  align-items: center;
  background-color: #3a3a3a;
}

#main-holder {
  width: 50%;
  height: 70%;
  display: grid;
  justify-items: center;
  align-items: center;
  background-color: white;
  border-radius: 7px;
  box-shadow: 0px 0px 5px 2px black;
}

#login-error-msg-holder {
  width: 100%;
  height: 100%;
  display: grid;
  justify-items: center;
  align-items: center;
}

#login-error-msg {
  width: 23%;
  text-align: center;
  margin: 0;
  padding: 5px;
  font-size: 12px;
  font-weight: bold;
  color: #8a0000;
  border: 1px solid #8a0000;
  background-color: #e58f8f;
  opacity: 0;
}

#error-msg-second-line {
  display: block;
}

#login-form {
  align-self: flex-start;
  display: grid;
  justify-items: center;
  align-items: center;
}

.login-form-field::placeholder {
  color: #3a3a3a;
}

.login-form-field {
  border: none;
  border-bottom: 1px solid #3a3a3a;
  margin-bottom: 10px;
  border-radius: 3px;
  outline: none;
  padding: 0px 0px 5px 5px;
}

#login-form-submit {
  width: 100%;
  padding: 7px;
  border: none;
  border-radius: 5px;
  color: white;
  font-weight: bold;
  background-color: #3a3a3a;
  cursor: pointer;
  outline: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <link rel="stylesheet" href="login.css">
  <script type="text/javascript" src="login.js"></script>

</head>

<body>
  <main id="main-holder">
    <h1 id="login-header">Login</h1>
    
    <div id="login-error-msg-holder">
      <p id="login-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
    </div>
    
    <form id="login-form">
      <input type="text" name="username" id="username-field" class="login-form-field" placeholder="Username">
      <input type="password" name="password" id="password-field" class="login-form-field" placeholder="Password">
      <input type="submit" value="Login" id="login-form-submit" onclick="validate_login()">
    </form>
  
  </main>
</body>

</html>

Although the HTML and CSS components function correctly, I encountered issues with the JavaScript implementation. Despite expecting an alert upon clicking the submit button, nothing occurs when I test it. The javascript should verify the username and password, then redirect the page accordingly. Any assistance would be greatly appreciated. Thank you!

Answer №1

In a response, j08691 highlighted that the click event handler in your code is creating the event listener after the first click. To address this issue, they suggested removing function validate_login() { along with the corresponding }, and eliminating the onclick attribute from the HTML.

const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-form-submit");
const loginErrorMsg = document.getElementById("login-error-msg");

loginButton.addEventListener("click", (e) => {
    e.preventDefault();
    const username = loginForm.username.value;
    const password = loginForm.password.value;

    if (username === "user" && password === "web_dev") {
        window.location.href="https://airtable.com"
    } 
    else {
        loginErrorMsg.style.opacity = 1;
    }
})
html {
    height: 100%;
  }
  
body {
  height: 100%;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  display: grid;
  justify-items: center;
  align-items: center;
  background-color: #3a3a3a;
}

#main-holder {
  width: 50%;
  height: 70%;
  display: grid;
  justify-items: center;
  align-items: center;
  background-color: white;
  border-radius: 7px;
  box-shadow: 0px 0px 5px 2px black;
}

#login-error-msg-holder {
  width: 100%;
  height: 100%;
  display: grid;
  justify-items: center;
  align-items: center;
}

#login-error-msg {
  width: 23%;
  text-align: center;
  margin: 0;
  padding: 5px;
  font-size: 12px;
  font-weight: bold;
  color: #8a0000;
  border: 1px solid #8a0000;
  background-color: #e58f8f;
  opacity: 0;
}

#error-msg-second-line {
  display: block;
}

#login-form {
  align-self: flex-start;
  display: grid;
  justify-items: center;
  align-items: center;
}

.login-form-field::placeholder {
  color: #3a3a3a;
}

.login-form-field {
  border: none;
  border-bottom: 1px solid #3a3a3a;
  margin-bottom: 10px;
  border-radius: 3px;
  outline: none;
  padding: 0px 0px 5px 5px;
}

#login-form-submit {
  width: 100%;
  padding: 7px;
  border: none;
  border-radius: 5px;
  color: white;
  font-weight: bold;
  background-color: #3a3a3a;
  cursor: pointer;
  outline: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <link rel="stylesheet" href="login.css">
  <script type="text/javascript" src="login.js"></script>

</head>

<body>
  <main id="main-holder">
    <h1 id="login-header">Login</h1>
    
    <div id="login-error-msg-holder">
      <p id="login-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
    </div>
    
    <form id="login-form">
      <input type="text" name="username" id="username-field" class="login-form-field" placeholder="Username">
      <input type="password" name="password" id="password-field" class="login-form-field" placeholder="Password">
      <input type="submit" value="Login" id="login-form-submit">
    </form>
  
  </main>
</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

Looking to include a toggle button in the menu for both desktop and mobile versions using Bootstrap

When viewing the website on a mobile device, the menu appears as a toggle button. However, on desktop, the menu is displayed without the toggle. Is there a way to show the menu in a toggle button on the desktop version using Bootstrap? ...

modification of the tooltip's background shade on Google Maps

Currently, I am using Google Chart to display data for different countries. When hovering over these countries, a tooltip is displayed which fetches data from the backend. However, I would like to customize the background color of this tooltip as it is cur ...

Interacting with a form in Node.js does not print out the form values to the

I am just starting to learn about node.js and I'm attempting to create a form that includes fields for 'name' and 'department'. However, when I submit the form, both 'name' and 'department' are showing up as &ap ...

PHP programming language for opening, editing, and saving HTML files

Trying to use PHP to open an HTML file, remove the content of a specific div (class Areas), and then save it. $dom = new DOMDocument; $dom->loadHTMLFile( "temp/page".$y.".xhtml" ); $xpath = new DOMXPath( $dom ); $pDivs = $xpath->query(".//div[@class ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

Tips for centering a background image:

I have been attempting to set a background image at the center, but all my efforts have failed. Here is the code I have tried: <a href="#" style="background-position:center center;"> <img src="https://firebasestorage.googleapis.com/v0/b/g ...

Parsing extremely large JSON data from a remote resource using NodeJS

I am facing a challenge with handling a very large JSON file (150k lines, ~3mb) obtained from an external source within my NodeJS application. Currently, I have been fetching the file using an AJAX call, parsing it, and storing it in cache: var options = ...

Passing a unique data value from Ajax to PHP using Ajax and PHP techniques

Currently, I'm working with Google Charts to set up various line charts. These charts are using data from a MySQL database, which is retrieved through an Ajax call to a PHP script. Right now, I have everything working smoothly by manually inputting t ...

Encountered a MultiValueDictKeyError in Django at /employeeUpdate/ after making changes to the data

Encountering a django error "MultiValueDictKeyError at /employeeUpdate/ 'id'" after making changes to the data. Here is the code snippet from my views.py: def employeeUpdate(request): id = request.POST['id'] emp_username = requ ...

Inquire: How can I transfer a value from one form to another HTML document, and then retrieve and utilize the value in JavaScript?

My goal in Express is quite complex, as I need to retrieve data from the form located in 'inputdata.html' (with a ROUTE of '/inputdata'). This data will then be passed to 'info.html' (with a ROUTE of '/info') Once ...

Automatically resizing font to fit the space available

I am attempting to achieve the task described in the title. I have learned that font-size can be set as a percentage. Naturally, I assumed that setting font-size: 100%; would work, but unfortunately it did not. For reference, here is an example: http://js ...

Error encountered: "Unable to process Three.js FontLoader due to SyntaxError

I attempted to generate 3D text with FontLoader in Three.js, but encountered an error. My Three.js version is r99. const loader = new THREE.FontLoader(); //https://github.com/mrdoob/three.js/tree/dev/examples/fonts loader.load("./fonts/helvetiker_ ...

Convert JavaScript objects into HTML format

Alright, I've got some JavaScript that's fetching data from a JSON file through a URL. Now, my goal is to convert each object (author_name, rating, author_url) into JavaScript IDs so that I can easily reference them in my HTML. For instance: &l ...

Creating personalized columns in a BootstrapVue table

I'm having an issue with the b-table component in bootstrap-vue. The array containing my items is structured like this: [{ id: 1, name: "Test", phone: 555-111-666, address: "Some Address", //etc... }] I have a couple of question ...

Guarantee of SQL integration within JavaScript

I am trying to retrieve the value of the message variable, but all I see in the console is the following: result [object Promise] async function Testing() { let response = await new Promise((resolve, reject) => { db.query("SELECT * FROM `ni ...

Methods for verifying if a file is included in another file, while disregarding any whitespace adjustments

Let's say I have multiple CSS files (a.css, b.css, ..., e.css) and after concatenating and compressing them, I get a new file called compressed.css. Now, I need to verify if each of the original CSS files is included in the compressed.css file. Are th ...

Web Scraping for Results on Android

Hello, I am embarking on a new endeavor in Android Studio where I am attempting to build an application that can submit a form on a website's HTML and then parse the resulting HTML page for data. While I have some experience with Jsoup in the past, my ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Upon migrating from Vue CLI 2 to 3, an error is thrown stating: "Cannot locate element: #app" and an empty body is

Currently, I am in the process of transitioning my VueJS project from VueCLI 2 to version 3. After moving all the necessary files to the src folder, I attempted to view it in the browser by running npm run serve. However, I encountered a problem where the ...