Reputation: 1681
jQuery 1.7.1 - I have an array of input text elements (class - pr) and same number of array elements for label (class - err). I have some validation on blur of the text box and would like to assign a error message to the label associated with the text box. The following jQuery code is not working.
HTML
<tr>
<td>
<label class="err" style="display: none;" for="prd"></label>
<input type="text" class="pr" name="prd" />
</td>
</tr>
jQuery
$("input.pr:text").blur(function(event){
// .... validation code
var index = $.inArray(this, $("input.pr:text"));
$("label.err")[index].show();
$("label.err")[index].text("Enter a number");
});
Upvotes: 0
Views: 1385
Reputation: 846
One liner:
$('label.err').eq(index).show().text('Enter a number');
or probably better:
$("input.pr:text").blur(function(event){
$(this).prev('label').show().text("Enter a number");
});
Upvotes: 2
Reputation: 102743
Once you reference a JQuery object using the index, it's no longer a JQuery object but a plain DOM element. Use the following instead:
var el = $($("label.err")[index]);
el.show();
el.text("Enter a number");
Upvotes: 1