I created the function to display the alert message on keypress then if the user does not include "@" in the field, it should keep showing but once "@" is added then the alert message should disappear.
Here is the code:
function makeHappen() {
var take = document.getElementById('emailID');
var a = document.getElementById("alert3second");
if (!take.value.indexOf("@") > -1) {
a.style.display = "block"
} else {
a.style.display = "none"
}
}
<div class="form-group">
<input type="email" class="form-control font-weight-bold" placeholder="YOUR EMAIL ADDRESS" id="emailID" onclick="formValidator2()" name="budget3" onkeypress="makeHappen()" required>
<div id="alert3" class="alert-danger">
<i class="fa fa-warning pr-2 pt-1"></i>
Please Your email address is required
</div>
<div id="alert3second" class="alert-danger">
<i class="fa fa-warning pr-2 pt-1"></i>
Enter a valid email
</div>
</div>
The logic of your if statement needs to be made clearer:
if (take.value.indexOf('@') == -1)
You can test this by running your current if statement like so:
> !"hello".indexOf("@") > -1
true
> !"hello@".indexOf("@") > -1
true
I would probably point out that you should name your variables a bit better. Maybe instead of 'take' you should call it emailID?
function validateEmail() {
var emailId = document.getElementById('emailID').value;
var errorMsg = document.getElementById('alert3second');
if (emailId.indexOf('@') == -1) {
errorMsg.style.display = 'block';
} else {
errorMsg.style.display = 'none';
}
}
instead of using onkeypress use onkeyup
The onkeyup attribute fires when the user releases a key (on the keyboard). https://www.w3schools.com/tags/ev_onkeyup.asp
and add style="display:none;" to alert3second div to make the message disappears when there is no value in the input
function makeHappen() {
var take = document.getElementById('emailID');
var a = document.getElementById("alert3second");
if (take.value.indexOf("@") == -1) {
a.style.display = "block"
} else {
a.style.display = "none"
}
}
<div class="form-group">
<input type="email" class="form-control font-weight-bold"
placeholder="YOUR EMAIL ADDRESS"
id="emailID" onclick="formValidator2()"
name="budget3" onkeyup="makeHappen()" required>
<div id="alert3" class="alert-danger">
<i class="fa fa-warning pr-2 pt-1"></i>
Please Your email address is required
</div>
<div id="alert3second" class="alert-danger" style="display:none;">
<i class="fa fa-warning pr-2 pt-1"></i>
Enter a valid email
</div>
</div>