Monday, November 15, 2010

(ZT)How To Check If Checkbox Is Checked

While working on my previous project I needed a way to check if the certain checkbox is checked or not. jQuery is a great library but I had a hard time identifying if any particular checkbox was checked. So here is the way to do just that.

All you need to do is to check checked attribute of checkbox HTML tag:

// First way 
$('#checkBox').attr('checked');

// Second way
$('#edit-checkbox-id').is(':checked');

// Third way for jQuery 1.2
$("input[@type=checkbox][@checked]").each(
    function() {
       // Insert code here
    }
);
// Third way == UPDATE jQuery 1.3
$("input[type=checkbox][checked]").each(
    function() {
       // Insert code here
    }
);

// In his comment Andy mentions that the 3rd method
// does not work in Firefox 3.5.2 & jQuery 1.3.2


First two methods return true or false. True if that particular checkbox was checked or false if it is not checked. The third method iterates though all checkboxes with checked attribute defined and performs some action.

0 Comments:

Post a Comment

<< Home