1
votes

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

4

4 Answers

2
votes

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);
        }
    }
});
1
votes

Here's a generic solution that will work with all checkboxes on the page. It will insert an error message after the last checkbox of the group.

$('form').validate({
    rules: {
        checkbox_group_1: {
            required: true
        },
        checkbox_group_2: {
            required: true,
        }
    },
    errorPlacement: function(error, element) {
        if (element.is(':checkbox'))
            error.insertAfter($('input[name=' + element.attr('name') + ']').last());
        else
            error.insertAfter(element);
    }
});
0
votes

Couldn't you just do

if(checkboxes.contains(element)) {
  checkboxes.after(label);
}
0
votes

What is the variable 'label' doing in your code?

Shouldn't you use the 'error' variable?

error.insertAfter(checkboxes[checkboxes.length-1]);