I have a form that i’m trying to use the jquery validate plugin. My problem is that i can’t access the label in the success callback. I can get label.attr('for'), but when i try label.attr('id'), or label.html(), i get undefined.
Here’s my validate call:
<script type="text/javascript">
$(document).ready(function() {
$('#personal_info').validate({
rules: {
LastName: "required",
Age: "required"
},
messages: {
LastName: "",
Age: ""
},
errorPlacement: function(error, element) {
console.log('element.attr = '+element.attr('name'));
if(element.attr('name') == 'Age') {
console.log('element = '+element.parents().siblings('label').html());
element.parents().siblings('label').removeClass('highlight').addClass('warning');
}
//error.insertBefore(element.parent().children("br"));
},
// specifying a submitHandler prevents the default submit, good for the demo
submitHandler: function() {
document.personal_info.submit();
},
validClass: "checkmark",
// set this class to error-labels to indicate valid fields
success: function(label) {
console.log('the label for = '+label.attr('for'));
console.log('the label id = '+label.attr('id'));
}
});
});
</script>
Here’s a piece of my html:
<label for="Age" id="age18" class="highlight"> Are you at least 18 years of age?</label>
<table id="OnlineAppWizard_InputAge18" border="0">
<tr>
<td>
<input id="Age18_yes" type="radio" name="Age" value="Yes" <?
if ($Age18 == "Yes") {
print "checked";
}
?>/>
<label for="Age18_yes">Yes</label>
</td>
<td>
<input id="Age18_no" type="radio" name="Age" value="No" <?
if ($Age18 == "No") {
print "checked";
} ?>/>
<label for="Age18_no">No</label>
</td>
</tr>
</table>
When i click on one of the radio buttons, this is what appears in the firebug console:the
the label for = Age
the label id = undefined
You can see from the html snippet that the label tag with the “for” attribute of “Age”, also has an “id” attribute of “age18”
The
labelparameter passed to thesuccesscallback is not the label you think it is. The jQuery Validation plugin generates error labels for each element to display error messages. It is this generated label that is passed to thesuccesscallback. You can see this by addingconsole.log(label);as the first line of the callback. It will return the following:FYI, that label is created in the
showLabelmethod of the validator. It is also the same element that is passed as theerrorparameter of theerrorPlacementmethod. Generally, theerrorelement would be appended to the form element that caused the error (i.e., failed to validate).To access the original label from the
successcallback, you will need a more direct approach.One solution, and very specific to this particular label, is to simply access it by it’s ID, e.g.
A more generic solution would be:
I have included both solutions in the live demo linked below.
Live Demo