Reputation: 79
I know this is stupid but i don't know why my validation function doesn't work. It keeps blinking "Need to fill both input !!!" . Pls help me
Here is my code:
<div class="container">
<h2>Login form</h2>
<form action="signin.php" method="POST" onsubmit="return validation();">
<h3 id='error'></h3>
<div class="form-group">
<label>Username:</label>
<input name="username" type="text" class="form-control" id="userName" placeholder="Enter username">
</div>
<div class="form-group">
<label>Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button name="login" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
function validation(){
var username = document.getElementById('userName').value;
var password = document.getElementById('password').value;
var error = document.getElementById('error');
if(username === "" || password === ""){
error.innerHTML="Need to fill both input !!!"
setTimeout(()=>error.remove(),3000);
return false;
}
return true;
}
Upvotes: 0
Views: 313
Reputation: 31
Probably you have misspelling in
getElementById('user**N**ame')
It should be in lowercase
- username
Upvotes: 0
Reputation: 198436
As stated in comments, the first time validation happens, you remove your error
element. It finishes fine, but with dire consequences. The second time validation happens, document.getElementById('error')
will give you undefined
, causing error.innerHTML=
to fail, which means the function does not return false
or prevent default, so the submit
event is free to continue unimpeded.
Instead of removing error
, empty it (the same way you filled it is fine).
setTimeout(() => error.innerHTML = "", 3000);
Upvotes: 2