johnny lee
johnny lee

Reputation: 17

Validate Multiple Groups of checkboxes in the same form jQuery

I am pretty new to jQuery and I need to have at least one checkbox checked in a group of checkboxes of the same form. here is a JSFiddle

HTML:

<form>
    <!-- CHECKBOX GROUP NUMBER ONE -->
     <h3>group one</h3>

    <input type="checkbox" class="reqNow" name='part1'>
    <input type="checkbox" class="reqNow" name='part1'>
    <br>
    <br>
    <!-- CHECKBOX GROUP NUMBER TWO -->
     <h3>group two</h3>

    <input type="checkbox" class="reqNow" name='part2'>
    <input type="checkbox" class="reqNow" name='part2'>
    <!-- CHECKBOX GROUP NUMBER THREE -->
     <h3>group three</h3>

    <input type="checkbox" class="reqNow" name='part3'>
    <input type="checkbox" class="reqNow" name='part3'>
    <!-- CHECKBOX GROUP NUMBER FOUR -->
     <h3>group four</h3>

    <input type="checkbox" class="reqNow" name='part4'>
    <input type="checkbox" class="reqNow" name='part4'>
    <br>
    <input type="submit">
</form>

JAVASCRIPT:

var submitOK = false;


$("form").submit(function (e) {
    e.preventDefault();


    var a = $(".reqNow").serializeArray();

    $.each(a, function (i, b) {
        if (b.value == "on") {
            submitOK = true;
        }


        if (submitOK) {
            alert("Form Sent!");
        }
    });

});

so basically I want the form to send only when there is at least one checkbox checked in each group.

any help is appreciated!

Upvotes: 0

Views: 926

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

You can check analogous to this answer JQuery Multiple Checkbox Groups Validation

$("form").submit(function (e) {
    e.preventDefault();
    var g1 = $('.reqNow[name=part1]:checked').length;
    var g2 = $('.reqNow[name=part2]:checked').length;
    var g3 = $('.reqNow[name=part3]:checked').length;
    var g4 = $('.reqNow[name=part4]:checked').length;
    if (g1 > 0 && g2 > 0 && g3 > 0 && g4 > 0)
        alert('Form sent!');
});

See modified JSFiddle

Upvotes: 1

Related Questions