jquery - how to use errorPlacement for a specific element?

freedayum picture freedayum · Oct 27, 2010 · Viewed 41k times · Source

I have checkbox and a text follows it, like;
[checkbox] I agree

If the checkbox is not clicked when submitting, the current way of showing the error msg I have is(I use errorElement:"div");

[checkbox]
This field is required.
I agree**

I would rather like;
[checkbox] I agree
This field is required

Any idea how to get this done?.

The html wrap for the concerned checkbox and text elements I have is like this;
[div] [checkbox] I agree [/div] [div][/div]

I tried errorPlacment: as follows hoping to apply it just for that element alone;

...            
messages: {
    usage_terms: {
        required: "Must agree to Terms of Use.",
    //errorElement: "div"
    errorPlacement: function(error, element) {
        error.appendTo( element.parent("div").next("div") );
        }
    }
}
...


It didn't work. Any idea?.

Answer

Nick Craver picture Nick Craver · Oct 27, 2010

errorPlacement isn't underneath messages (as an option), it's a global option, so instead it should look like this:

messages: {
  usage_terms: "Must agree to Terms of Use."
}
errorPlacement: function(error, element) {
  if(element.attr("name") == "usage_terms") {
    error.appendTo( element.parent("div").next("div") );
  } else {
    error.insertAfter(element);
  }
}

Here's we're just checking the element name when deciding where it goes, you could do another check though, for example giving all the ones that behave like this a class, and doing element.hasClass("placeAfter").