Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Check if Checkbox is Checked

I'd like to figure out how to write something like the following to validate single check boxes. There could be just one on the form or many separate ones. The example below doesn't work.

Thank you!

// -----------------------------------------------
// CHECK SINGLE CHECKBOX
// -----------------------------------------------
$('.mcCbxRequired').each(function() {
    var mcCbxCheck = $(this);
    if(mcCbxCheck.is(':checked')) {
        alert('checked');
        // do something here ...
    }
    else{
        alert('not checked');
        return false;
    }
});
like image 870
user582065 Avatar asked Dec 23 '11 03:12

user582065


2 Answers

A couple things:

  1. Each applicable checkbox must have the mcCbxRequired class. If neither alert shows, the problem must be because your checkbox does not have this class.

  2. You are returning false in both cases. That doesn't really make sense with validation, so you should change the relevant part of your code to this:

Code:

    if(mcCbxCheck.is(':checked')) {
        alert('checked');
        return true;
    }
like image 146
Devin Burke Avatar answered Oct 02 '22 16:10

Devin Burke


You can use:

$('input[type=checkbox]:checked').each(function()
{
   var checkedBox = $(this);

   // Do whatever you want
});

Also, JQuery selectors by Class are slower than by id/by type.

like image 25
Varun Goel Avatar answered Oct 02 '22 14:10

Varun Goel