How to check if checkbox is checked using jQuery

I needed to find if a checkbox was checked in jquery but I knew of multiple ways to do this. But I wasn’t sure of the best way to perform this task. Still I haven’t decided on the best way to do this so I was hoping someone with much greater knowledge than me in the inside-outs of the jQuery could help me out here. Out of the following examples what would be the best way to discover if a checkbox has been checked or not.

Using Attribute Method

This will check to see if there is an attribute on the element which is called checked.

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

Using the IS Method Selector

This method will check to see if the element is checked.

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

Checked Selector

Get all elements which are currently checked by using the following snippet.

$('.selector:checked')

Using @ Attribute Method

This will use a @ selector which will define a search for an attribute on the element.

So the below code will search for any element with type checkbox and if it 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   
    }   
);

Advertise here

Comment