Reputation: 47
I am trying to direct to another file after successful login. However, it doesn't seem that I was able to go to b.html after login successfully alert is displayed. It seems to be remain in the same page. I have tried document.location.href
, window.location.replace
but it doesn't seem to work
<script>
window.onload = function() {
document.addEventListener("deviceready", init, false);
}
function init() {
document.getElementById("btnSave").addEventListener("click", saveData, false);
document.getElementById("btnGet").addEventListener("click", getData, false);
}
function getData() {
var email1 = document.getElementById("email1").value;
var pass1 = document.getElementById("password1").value;
var email2 = window.localStorage.getItem("email");
var pass2 = window.localStorage.getItem("pass");
if (email1 == email2 && pass1 == pass2) {
alert("Login successfully");
window.location.href = "/b.html";
} else {
alert("Invalid login credentials");
}
}
</script>
<form class="login-form">
<input type="email" id="email1" name="email1" placeholder="Email Address" required/>
<input type="password" id="password1" name="password1" placeholder="Password" required/>
<button id="btnGet" type="submit" name="submit">Login</button>
</form>
Upvotes: 1
Views: 2159
Reputation: 1992
The reason why your redirection doesn't work is that clicking the Login
button submits the form. This is a normal behaviour of the web browser. In your case you need to this prevent this default behaviour.
Using jQuery
, you can do it like this:
$('form.login-form').submit((e) => {
e.preventDefault();
});
Since you're not using jQuery
in your code at all, you might be interested in such a version:
form.addEventListener('submit', e => {
e.preventDefault();
});
An alternative solution would be not to add type="submit"
attribute to the login button.
But the best you can do (and what internet users are used to) is to redirect the user after submitting the form. Then this will work not only when a user clicks the button but when he presses ENTER
as well etc.
Then your code should look like this:
(() => {
let form;
function init() {
form = document.querySelector('login-form');
if (!form) {
throw new ElementNotFoundException();
}
form.addEventListener('submit', onSubmitHandler);
}
function onSubmitHandler(e) {
e.preventDefault();
// get values, validate...
window.location.href = 'b.html';
}
init();
});
Upvotes: 4
Reputation: 64
Maybe location href is not correctly writen, please replace window.location.href = "/b.html";
to window.location.href = "b.html";
Upvotes: 1