Reputation: 31
I'm not able to redirect to a single page using windows location in .js page.
However I checked with alert box to see whether the condition is passing true or not and it is working while location is not working.
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "[email protected]" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
I feel I'm missing something.
Upvotes: 0
Views: 230
Reputation: 1074305
I suspect you're calling validate
like this:
<form onsubmit="validate()" ...>
That won't use the return value of validate
to cancel the submit. You need a return
:
<form onsubmit="return validate()" ...>
Since the submission is not being cancelled, the form submission is a navigation action, which overrides your assignment to window.location.href
.
In a comment you've said you're doing this:
<button type="submit" name="submit" onclick="validate()" class="btn-secondary">Sign In</button>
If so, adding the return
to the onclick
should fix it on any modern browser:
<button type="submit" name="submit" onclick="return validate()" class="btn-secondary">Sign In</button>
But I would move it to an onsubmit
on the form
instead.
Side note: There's no need for the type="submit"
on that button. submit
is the default type for button
elements.
Upvotes: 2
Reputation: 410
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "[email protected]" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
}
return false; // ALWAYS return this. else it will proceed with page submit.
}
}
Upvotes: -1