Home > Mobile >  Simple Login Form
Simple Login Form

Time:01-03

I am trying to implement a simple login form using JavaScript and HTML. When I submit the form, I want to check the username and password against a list of valid credentials.

If the credentials are valid, I want to redirect the user to the home page. Otherwise, I want to show an error message. I have written the following code, but it is not working as expected. Can someone please help me debug this issue?

<form id="login-form">
  <label for="username">Username:</label><br>
  <input type="text" id="username" name="username"><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password"><br><br>
  <input type="submit" value="Submit">
</form>

<script>
  const form = document.getElementById('login-form');
  const username = document.getElementById('username');
  const password = document.getElementById('password');

  form.addEventListener('submit', function(event) {
    event.preventDefault();

    const validCredentials = [
      { username: 'user1', password: 'pass1' },
      { username: 'user2', password: 'pass2' }
    ];

    for (const credential of validCredentials) {
      if (credential.username === username.value && credential.password === password.value) {
        window.location.href = '/home';
      } else {
        alert('Invalid username or password');
      }
    }
  });
</script>

I am implement a simple login form using JavaScript and HTML.

The expected outcome of the code is that when the user enters a valid username and password and clicks the submit button, they will be redirected to the home page. If the username and password are invalid, an error message should be displayed.

CodePudding user response:

First of all, don't do this if you want to use this code for real users and production web app. It's not a good approach to hardcore users or passwords in a JavaScript script. If you are using this code for learning purposes, it's okay!

Secondly, the code has two meaningful problems. The alert inside the else block is running after every iteration of the for loop. You have to add a return statement to stop the loop and exists the function. Place the alert after the for loop, because the intention of the alert (I guess) is: if you don't find any coincidence, show to the user that the username and password are invalid.


 for (const credential of validCredentials) {
      if (credential.username === username.value && credential.password === password.value) {
        return window.location.href = '/home';
      }
    } //end of the loop
    
  alert('Invalid username or password');

  }); //end of the callback function

});

On the other hand, in window.location.href = '/home', the string is a malformed URI. You have to send user to a completed URI like, https://google.com/ or http:/yoursite.com/home

  • Related