Reputation: 1632
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.
Upvotes: 0
Views: 163
Reputation: 82933
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");
}
});
Upvotes: 2
Reputation: 349102
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");
}
});
Upvotes: 2
Reputation: 30145
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");
}
});
Code: http://jsfiddle.net/6dWFs/
Upvotes: 2