Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - how to use errorPlacement for a specific element?

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?.

like image 494
freedayum Avatar asked Oct 27 '10 11:10

freedayum


1 Answers

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").

like image 185
Nick Craver Avatar answered Oct 16 '22 20:10

Nick Craver