t56k
t56k

Reputation: 6981

jQuery: check if checkboxes are checked

I want to highlight any unchecked checkboxes when a form is submitted. I've got a total of six checkboxes in .new_order, and I've started writing the function but I'm a bit stuck how to add a highlight class to each unchecked checkbox in .new_order.

$('#orderconfirm').click(function () {
    if ($('.modal .modal-body .new_order :checkbox').is(':unchecked') {
        $(this).addClass('highlight');
    }
});

Will this code iterate through each checkbox? I feel like I'm missing something. Also, this code has to disable the button until each checkbox is checked. Any help would be great!

Upvotes: 0

Views: 1384

Answers (2)

dsgriffin
dsgriffin

Reputation: 68596

Here is a working jsFiddle of the following method.

You could use jQuery's each() to iterate through your class, and add your CSS class to whichever elements meet your criteria:

$('#orderconfirm').click(function () {
  $('.new_order').each(function(){
     if($(this).prop('checked') === false) {
        $(this).addClass('highlight');
     }
  });
});

Upvotes: 2

Daniel Imms
Daniel Imms

Reputation: 50189

Try using :not(:checked) at the end of your selector, call .addClass() on this to add the class to all objects returned.

Demo

$('#orderconfirm').click(function () {
    $('.modal .modal-body .new_order input:checkbox:not(:checked)')
        .addClass('highlight');
});

Upvotes: 2

Related Questions