I have created a login page where I can login with my username and password and it is working fine when I validated it with JavaScript using onsubmit attribute in the form tag. But when i modify it to add innerhtml to my h3 tag where I want to show Wrong Credential when user input wrong username or password then it is not showing the same and also it is been redirected to the successful login page even when I have added return false statement in JavaScript.
function validate(){
var uname=document.getElementById('username').value;
var password=document.getElementById('password').value;
var users=["mustafa","param","swapnil","abhi"];
var pwd=["1234","4567","8524","7418"]
for (let i = 0; i < users.length; i++) {
if((uname==users[i])&&(password==pwd[i])){
location.href("sucess.html");
return true;
}
}
document.getElementById('wrong').innerHTML="Worng details";
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="index_js.js"></script>
</head>
<body>
<h3 id="wrong" style="background-color:red"></h3>
<form action="sucess.html" onsubmit="return validate()">
<label for="uname">User Name</label>
<input id="username" type="text"> <br> <br>
<label for="pwd">Password</label>
<input type="password" id="password"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
>Solution :
It doesn’t return true.
location.href is a string, not a function. Trying to call it as a function throws an exception and terminates the script.
Since the script terminates, the function doesn’t return false, so the default behaviour of the event handler is never prevented and the form submits as normal.
If you want to navigate using location.href you need to assign a new value to it with = … but then the function will return true and the form submission will replace that navigation instruction so it won’t have any effect.