jQuery Validation Plugin Checkbox errorPlacement

Ian McCullough picture Ian McCullough · Jul 6, 2009 · Viewed 7.3k times · Source

I have a group of checkboxes that all have the same name. They all have different values. They are just part of a form. They do not make up the entire form. I want the checkboxes to display their error AFTER the last checkbox of that group.

is it possible to do something like this in jQuery?

$("#myform").validate({
  errorPlacement: function(error, element) {
     var checkboxes = $("#checkboxes");
     if(checkboxes.contains(element))
        label.insertAfter(checkboxes[checkboxes.length-1]);
   },
   debug:true
 })

How would I go about doing this?

Thanks,
Ian McCullough

Answer

JohnEric picture JohnEric · May 14, 2010

I realize that this is an older question but, I needed similar functionality on a form and solved it.

Using jQuery 1.4.2

So given the following form.

<form id="checkForm" method="get" action="">
<ul id="checkboxes">
    <li><input type="checkbox" name="checkOne" id="checkOne" value="1" /></li>
    <li><input type="checkbox" name="checkTwo" id="checkTwo" value="2" /></li>
    <li><input type="checkbox" name="checkThree" id="checkThree" value="3" /></li>
</ul>
<input class="submit" type="submit" value="Submit"/>

Then you can do the following

$("#checkForm").validate({
    rules: {
        checkOne: "required",
        checkTwo: "required",
        checkThree: "required"
    },
    errorPlacement: function(error, element) {
        if ($("#checkboxes").has(element).size() > 0) {
            error.insertAfter($("#checkboxes input:checkbox:last"));
        } else {
            error.insertAfter(element);
        }
    }
});