JQuery validation - how to set the title attribute to the error message
In JQuery validation the default behavior on an error is to create a label like so:
<label for="FirstName" generated="true" class="error">This field is required.</label>
Is it possible to change it so that it will output this instead (with a title attribute set to the error message)?
<label for="FirstName" generated="true" class="error" title="This field is required.">This field is required.</label>
I've tried the highlight method, but the label has not been created yet:
$("#form").validate({
highlight: function (element, errorClass) {
var label = $("label[for=" + element.id + "]"); // but label doesn't exist yet so this doesnt work
if (label &&开发者_StackOverflow中文版; label.length > 0) { // label.length is always 0
label.attr('title', label.text());
}
}
});
ok try this...
$("#form").validate({
highlight: function (element, errorClass) {
setTimeout(function() {
var label = $("label[for=" + element.id + "]");
if (label && label.length > 0) {
label.attr('title', label.text());
}
}, 10);
}
});
basically we just delay the part where we set the title attribute for 10ms so we are sure that the label element is created first.
hope this helps
try this instead.
var validator = $('#form1').validate({
highlight: function (element, errorClass, message) {
var errorMessage = validator.errorMap[element.name]
$(element).attr('title', errorMessage);
}
});
no hacks required
I'am a bit late, but stumbled upon this question, and another solution would be to use the errorPlacement callback.
editid: also remove the generated attribute, else the message text gets refreshed after editing the field when the message is re-applied.
var validator = $('#form1').validate({
errorPlacement: function(error, element) {
element.attr('title', error.text());
error.text('!');
error.removeAttr('generated');
error.appendTo(element.parent());
return true;
}
}
精彩评论