Prince Prince - 1 year ago 94
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=""></script>
$(document).ready(function() {
$(".form-register").submit(function (e) {


$(".error").animate({'margin-left': '0'});

var email = $(this).find('input[name="email"]').val();
alert('Email can not be empty');

var name = $(this).find('input[name="name"]').val();
alert('Name can not be empty');

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



.form-register input.error {
border:1px solid #F5192F;
box-shadow:0 0 4px #F5192F;

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

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

Answer Source

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.').

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download