Reputation: 61
I am using jquery validator to validate form fields. For below fields:
Focus is at third field i.e email 2 but I want focus on first field i.e fax.
Error message is displayed between text both and other static text due to which alignment shifts here and there. Best possible way to display messages.
In few scenarios only error message is displayed but not focus due to which user is not aware of error.
Code:
var validator = $("#enrollmentForm").validate({
errorElement: 'label',
errorPlacement: function(error, element) {
error.insertAfter(element);
element.focus();
},
});
Can someone provide a solution?
Upvotes: 0
Views: 7759
Reputation: 98728
Your own code is causing the problem you're describing.
errorPlacement: function (error, element) {
error.insertAfter(element);
element.focus(); // <- this line is causing your whole problem
},
By using element.focus
within errorPlacement
, you're telling it to focus on the element being evaluated right when it's been evaluated. If mutiple elements are invalid at once, then focus is naturally left on the very last one that was evaluated, since the form is evaluated from top to bottom.
Demo of the problem caused by your own code: http://jsfiddle.net/6y3k6jtc/
Removing the element.focus()
line totally fixes your code, because you're allowing the plugin's default focus to operate as intended. (By default, the plugin automatically knows to place focus on the very first invalid input element.)
errorPlacement: function (error, element) {
error.insertAfter(element);
},
DEMO of working code: http://jsfiddle.net/6y3k6jtc/1/
Upvotes: 0
Reputation: 11693
Use
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
validator.errorList[0].element.focus();
}
}
Upvotes: 1