jQuery: the correct event to handle checkboxes is change()

Checkboxes are easily handled with jQuery only if we know what's the correct event to be associated with them. Most people think that since we click on them, then the correct event is surely click. They're wrong. The correct event to be used with checkboxes is change. Let's see an example.

Suppose that we have an ordered list and we want to select only the even items when a user selects a checkbox. At the same time, when such a user deselects the checkbox, the previously selected items should return to their normal state.

So this is an on/off action. First, let's create some sample functions to associate actions with the checkbox:

var selectEven = function(element) {
    var $index = element.index() + 1;
    if ($index % 2 == 0) {
        element.addClass('even');
    }

};

var makeEven = function(elements) {
    elements.each(function() {
        var elem = $(this);
        selectEven(elem);
    });
};

var undoEven = function(elements) {
    elements.each(function() {
        var elem = $(this);
        if (elem.hasClass('even')) {
            elem.removeClass('even');
        }
    });
};

To test if a checkbox is checked we can safely use the prop() method combined with the change event:

var $elements = $('li', '#form');


$('#test').change(function() {
    var $checkbox = $(this);
    if ($checkbox.prop('checked')) {
        makeEven($elements);
    } else {
        undoEven($elements);
    }
});‚Äč

You can see the demo below.

Demo

Live demo

Articles