简体   繁体   中英

Two groups of checkboxes, how to throw validation error if at least one checkbox is not checked in either group

Total jQuery n00b. I have the following (simplified) form with two categories/groups of checkboxes (leaving out all other inputs):

<form id="myForm" method="post">
    Category 1:
    <input type="checkbox" name="check1" id="check1" value="1" />
    <input type="checkbox" name="check2" id="check2" value="2" />
    ...
    Category 2:
    <input type="checkbox" name="check3" id="check3" value="3" />
    <input type="checkbox" name="check4" id="check4" value="4" />
    <input type="submit" />
</form>

I am trying to throw a client-side validation error if, after a submit, no checkbox is checked in Category 1 or if no checkbox is checked in Category 2.

Again, being a jQuery n00b, I've seen some examples that throw the error to a pop-up box. However, what I want is for an error to be thrown in the validation error <div> that is set up using jquery.unobtrusive.validation (can't remember the exact name). Also, that the names are all different prevents me from using some of the easier examples out there.

The checkboxes are actually booleans (cannot use a checkbox list in this instance) in my model, using ASP.net MVC. I would, therefore, actually have the code: @Html.Checkbox(m => m.Model.Check1) and so on in my .cshtml view. I don't believe that's relevant. But I could be wrong.

Easiest way:

if ($('#check1,#check2').filter(':checked').length <= 0 || 
         $('#check3,#check4').filter(':checked').length <= 0) {
   // error message
}

You'll have to figure the rest out yourself, since you've posted no useful details about exactly HOW you're validating this form.

One way would be to give one class to the first group of checkboxes, say category1 , and another to the second group, such as category2 . Then you'd do something like

$("#myForm").submit(function() {
    if ($(".category1:checked").length == 0 || $(".category2:checked").length == 0) {
        $("#errormessage").append("<p>You must check at least one checkbox in each category!</p>"); // Or however you want the validation error to be displayed
        return false;
    }
});

But less repetitive would be to put a div or other container element around the checkboxes in each group, and then give each div its own class or ID (so you have one .category1 div that contains all the checkboxes in category 1 and one .category2 div containing all the checkboxes in category 2). Then you'd use $(".category1 :checked") and $(".category2 :checked") as the selectors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM