views:

27

answers:

1

When error messages appear in the form, they displace elements to the left. How can this be avoided?

Example

+1  A: 

You need to use a custom error element placement (this would go inside .validate() ) like:

errorElement: "div",
errorPlacement: function(error, element) {
      element.before(error);
}

This would insert a div containing the error message right before the form element that is generating the error. By altering the 3rd line in the given example, you can move that element wherever you want. For example, based on your code, to move it completely outside the table, you would use:

errorElement: "div",
errorPlacement: function(error, element) {
      element.parent().parent().parent().before(error);
}

... and that would place it right before the entire form. Of course, it would be much more elegant to simply designate an error area outside the form ...

<div id="error_goes_here"></div>
<form ...

... and then place the error there:

errorElement: "div",
errorPlacement: function(error, element) {
      $("#error_goes_here").html(error);
}

Depending on which way you decide to go, you might not even need to use errorElement, but just errorPlacement. The chosen answer to this question should also give you even more info on how to use it.

Hope this helps !


EDIT:

To position the error element to the right, add the error placement code inside .validate():

$("#commentForm2").validate({
    errorElement: "div",
    errorPlacement: function(error, element) {
        element.after(error);
    }
});

The generated error element is automatically assigned a class called .error, so, if needed, you can style with CSS:

div.error {
   // your CSS
}
FreekOne
My gaps in css annoy me here. I want each error message to appear at the side of its select, inside the table that contains the select, how would I do this?
omgzor
Would that be on the left, or on the right of the `select` element ?
FreekOne
on the right it is.
omgzor
Please see my updated answer.
FreekOne
Thanks, very helpful.
omgzor
Glad to be of help :)
FreekOne