jQuery and checkboxes, the complete guide.

Bookmark and Share
July 14, 2010 Category: Tutorials, jQuery Tips

jQuery is a great framework but sometimes the jQuery.com documentation is not enough to answer all your questions.
Here is a list of pretty much everything you can do with checkboxes.

Selecting / Unselecting a checkbox

// Check a checkbox
$('input[name=acheckbox]').attr('checked', true);
 
// Uncheck a checkbox
$('input[name=acheckbox]').attr('checked', false);

Selecting / Unselecting all checkboxes

// This will select all checkboxes
$("input:checkbox").attr('checked', true);
 
// This will unselect all checkboxes
$("input:checkbox").attr('checked', false);

Verifying if a checkbox is selected

// this will return true is the checkbox is checked, if not it will return false.
$('input[name=acheckbox]').is(':checked')

Getting a list of selected checkboxes

There are several ways to get a list the of selected checkboxes, here is my take on it.

// Extend jQuery with custom method
jQuery.fn.getCheckboxValues = function(){ 
    var values = []; 
    var i = 0; 
    this.each(function(){ 
        // push values into array
        values[i++] = $(this).val(); 
    }); 
    // return array of selected checkboxes
    return values; 
} 
 
var arr = $("input:checked").getCheckboxValues();
alert(arr); // this would alert an array containing the values of the selected checkboxes

2 comments so far

ben

Reply

instead of the i iterator I would just use values.push($(this).val()); in the loop, just my opinion

jQuery: manejo de checkbox | ilikeblues

Reply

[...] Vía | http://www.premiumbeat.com [...]

Add New Comment




Your Comment