True condition is never executed, instead the false condition is always executed. I cant seem it find what exactly I'm doing wrong.
<script>
$(document).ready(function(){
var userEmail = $('input#userEmail').val();
$("#email-submit").click(function(){
//False condition
if(!validateEmail(userEmail)) {
$('#emailErrors').text("Enter a valid Email");
}
//true conidition
if(validateEmail(userEmail)) {
alert("true");
$.post('includes/loginFunction.php', {userEmail: userEmail}, function (data){
$('#emailErrors').text(data);
});
}
});
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
</script>
You need to inspect input#userEmail
within your click handler. Otherwise, you have only stored what the value of the input was when the $(document).ready()
callback was executed.
$("#email-submit").click(function(){
var userEmail = $('input#userEmail').val();
if (!validateEmail(userEmail)) {
$('#emailErrors').text("Enter a valid Email");
} else {
// true condition
}
}
You also, as per above, can use else
instead of calling validateEmail
twice.
And further, in your validateEmail
function, you're declaring the parameter $email
. Usually, the convention for prefixing a $
before a variable is when you're caching a jQuery (or other library) object. You should probably switch this to simply email
.
https://jsfiddle.net/uf6Ld70f/
$(document).ready(function () {
$("#email-submit").click(function () {
var userEmail = $('input#userEmail').val();
//true conidition
if (validateEmail(userEmail)) {
alert("true");
$.post('includes/loginFunction.php', {
userEmail: userEmail
}, function (data) {
$('#emailErrors').text(data);
});
// false
}else{
$('#emailErrors').text("Enter a valid Email");
}
});
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.