HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Check whether all checkboxes are checked and then execute a function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkboxesareallandfunctionthencheckedcheckwhetherexecute

Problem

How could I make this code dry?

$("#btnSubmitToCheckOut").click(function(event) {
        var isSelected = [];

        $(".age_agree :checkbox").each(function() {
            if ($(this).is(":checked")) {
                isSelected.push("true");
            } else {
                isSelected.push("false");
            }
        });

        if ($.inArray("false", isSelected) < 0) {
            $(this).parents('form').submit();
        } else {
            alert('Please accept all the Terms and Conditions');
        }

    });

Solution

I was thinking something along these lines. The condition checks whether there are no unchecked checkboxes (length of the selection is 0) and then executes the appropriate branch.

$("#btnSubmitToCheckOut").click(function(event) {
    if ($('.age_agree input[type="checkbox"]').not(':checked').length == 0) {
        $(this).parents('form').submit();
    } else {
        alert('Please accept all the Terms and Conditions');
    }
});

Code Snippets

$("#btnSubmitToCheckOut").click(function(event) {
    if ($('.age_agree input[type="checkbox"]').not(':checked').length == 0) {
        $(this).parents('form').submit();
    } else {
        alert('Please accept all the Terms and Conditions');
    }
});

Context

StackExchange Code Review Q#70392, answer score: 5

Revisions (0)

No revisions yet.