Prince Prince - 4 months ago 9
Javascript Question

Display an alert when a condition is verify using jquery

I am working on a form. When no input field is empty, an alert is displayed. When an error occurs(empty field submitted), a class is added to the input to apply a style on it.



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".form-register").submit(function (e) {

e.preventDefault();

if($(this).find('.error')){
$(".error").animate({'margin-left': '0'});
$(this).find('input').removeClass('error');
$(this).find('select').removeClass('error');
}

var email = $(this).find('input[name="email"]').val();
if(!email){
$(this).find('input[name="email"]').addClass('error');
alert('Email can not be empty');
}

var name = $(this).find('input[name="name"]').val();
if(!name){
$(this).find('input[name="name"]').addClass('error');
alert('Name can not be empty');
}

if($(this).find('.error')){
$(".error").animate({'margin-left': '15px'});
}else{
alert('No error has been detected.');
}

});
});

</script>

<style>
.form-register input.error {
border:1px solid #F5192F;
box-shadow:0 0 4px #F5192F;
}
</style>

<form class="form-register" method="post" action="">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit"/>
</form>





I want to display an alert when the fields are not empty but no way. Kindly help me fix this problem. Thanks

Answer

if($(this).find('.error')) { will always be true as even if no element with class error is present in the form, jQuery will return an empty array. Change the code to if($(this).find('.error').length > 0){ to display the alert alert('No error has been detected.').