TF120 TF120 - 9 months ago 34
HTML Question

onclick if condition is met redirect with setTimeout

I'm trying to create a simple login example of where if the login details meet a certain username and password, then redirect to a different page after 3 seconds.

This is what i've attempted so far, any help is appreciated

<input type="text" id="username" placeholder="Username" name="uname" maxlength="15" required>

<input type="password" id="password" placeholder="Password" name="psw" maxlength="25" required>

<div id="loginButton">
<button type="button" input id="detailsChecker" onclick="showalert('alert');" label=>Login </button>
</div>

<div id="alert" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
<p id="alertmsg"> </p>
</div>

<div id="alertsuccess" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
<p id="alertmsg"> </p>




function showalert(id) {
var divelement = document.getElementById(id);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "u1460714" && password ==="barney") {
document.getElementById("alertmsg").innerHTML = "Successfully logged in, redirecting in 3 seconds";
setTimeout, window.location = "attendance.html"; 3000;
divelement.style.display = 'block';
divelement.className = 'success'

}
}

Answer Source

You have improperly called the setTimeout() function. It accepts an callback function as the argument, holding the whole code, which has to be delayed.

function showalert(id) {
  var divelement = document.getElementById(id);
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  if (username === "u1460714" && password === "barney") {
    document.getElementById("alertmsg").innerHTML = "Successfully logged in, redirecting in 3 seconds";
    setTimeout(function() {
      window.location = "attendance.html";
    }, 3000);
    divelement.style.display = 'block';
    divelement.className = 'success'
  }
}
<input type="text" id="username" placeholder="Username" name="uname" maxlength="15" required>

<input type="password" id="password" placeholder="Password" name="psw" maxlength="25" required>

<div id="loginButton">
  <button type="button" input id="detailsChecker" onclick="showalert('alert');" label=>Login </button>
</div>

<div id="alert" style="display:none;">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <p id="alertmsg"> </p>
</div>

<div id="alertsuccess" style="display:none;">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <p id="alertmsg"> </p>