Ninjakid Ninjakid - 22 days ago 6
HTML Question

javascript "if" statement not responding

i was trying out an HTML/JS login system, and everything was working correctly, except for an if statement that should activate when someone entered the correct username and password, but it did nothing, didn't even output the alert function.
here is the code i used:



var count = 2;

function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["Adam", "Adam2"];
var passwordArray = ["12345", "54321"];
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
valid = true;
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
var again = " tries";
if (count == 1) {
again = " try";
}
if (count >= 1) {
alert("Username and password do not match.");
count--;
} else {
alert("Username and password do not match. You are now blocked.")
document.login.username.value = "You are now blocked";
document.login.password.value = "You can not see this";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
}

<div class="container">
<div class="header">
<h1>Login Page</h1>
</div>

<form name="login" onsubmit="return validateForm();" method="post">

<ul>
<li>Username:
<input class="username" type="text" name="username">
</li>

<li>Password:
<input class="password" type="password" name="password">
</li>
</ul>

<input type="button" class="submit" value="Login" name="submit" onclick="validate()">
</form>
</div>




Answer

You are breaking the loop and your if(valid) code is within the for loop. You probably meant to have the if(valid) outside the for loop scope.

For example you can do:

valid = false;

for (var i = 0; i < usernameArray.length; i++) {
    if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
        valid = true;
        break;
    }
}

if (valid) {
    alert("Logging in...");
    window.location.href = "http://www.google.com";
    return false;
}

Notice I closed the for loop.

Also notice you have an valid=true after the if statement. I assume you did it for debugging purposes, but make sure to remove it.

Comments