I have particular css through which I am hiding image. Now I want to develop jquery through which if particular field is blank on blur than image of class error should be shown..
.error{
display:none;
}
<tr>
<th width="30%">Email:</th>
<td width="63%"><input type="text" name="email" id="email" title="Email*" class="validate"/></td>
<td width="05%"><img width="27" height="27" id="erroremail" src="images/error.png" alt="Error" title="N/A*" class="error"></td>
</tr>..
And I develop jquery for this is
$('.validate').blur(function() {
if ($(this).val() == '') {
$(this).next('.error').show().css({'display':'block'});
alert("null");
} else {
$(this).next('.error').hide();
alert("not null");
}
});
Though I am not getting any error on console. Even alert is also running but jquery is not working.
-
Are you binding the blur event in the jQuery ready event (i.e. after the DOM is loaded)?Chandu– Chandu2011年11月10日 18:35:53 +00:00Commented Nov 10, 2011 at 18:35
-
of course...I have done that.Rahul Singh– Rahul Singh2011年11月10日 18:37:23 +00:00Commented Nov 10, 2011 at 18:37
3 Answers 3
next() returns the immediately following sibling.
In your case there are no siblings for the .validate element, instead the elamenet you want to target is in the next table cell .
You have to use $('.error', $(this).parent().next()) to get hold of the .error element.
1) $(this).parent() -- return the parent td element.
2) next() returns the next td cell.
3) $(".validate", $(this).parent().next()) returns all the elements with validate class which are children of $(this).parent().next().
$('.validate').blur(function() {
if ($(this).val() == '') {
$('.error', $(this).parent().next()).show();
alert("null");
} else {
$('.error', $(this).parent().next()).hide();
alert("not null");
}
});
Comments
Your code doesn't find right element. Try this:
$('.validate').blur(function() {
if ($(this).val() == '') {
$(this).closest('tr').find('.error').show();
alert("null");
} else {
$(this).closest('tr').find('.error').hide();
alert("not null");
}
});
Comments
next() points to nothing, because you're in a table. First select the parent cell, then select the .error element:
$(this).parents('td:first').next().find('.error')
Final code:
$('.validate').blur(function() {
var errorImg = $(this).parents('td:first').next().find('.error');
if ($(this).val() == '') {
errorImg.show().css({'display':'block'});
alert("null");
} else {
errorImg.hide();
alert("not null");
}
});