When validating a password in a form, I have encountered an issue where the code only works for one specific outcome. If the correct password is entered, the user should be moved to site X, but if it's incorrect after 3 tries, they should be moved to site Y.
Unfortunately, the code seems to only redirect users to site Y regardless of whether the password is correct or not.
The code snippet being used:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the limit.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
I attempted the following solutions:
- Conducting thorough syntax error checks within the code.
- Changing
===
to==
under the assumption that the quotation marks may impact equality comparisons. - Testing
.window.location.href = 'http://maariv.co.il', true;
- Including
return false
immediately afterwindow.location.href
.
As a novice, I am puzzled as to why the conditional statement seems to partially work - with the negative part triggering correctly while the positive outcome fails to execute as intended.
Update:
This scenario is solely for practice purposes and will not be implemented in a live environment. In a production setting, it would be necessary to securely store and validate passwords through database interactions.