Skip to content

Instantly share code, notes, and snippets.

@developish
Created April 11, 2011 21:48
Show Gist options
  • Save developish/914437 to your computer and use it in GitHub Desktop.
Save developish/914437 to your computer and use it in GitHub Desktop.
Simple way to bind the state of a checkbox to an associated function.
// Bind a checkbox to a with checked and unchecked callback functions
// and run the appropriate action on page load:
//
// Examples
//
// $("input[type=checkbox][name=thecheckbox]").bindCheckbox({
// checked: function() {
// alert("the checkbox is checked!")
// },
// unchecked: function() {
// alert("the checkbox isn't checked!")
// }
// })
//
// Returns chainable jQuery object
$.fn.bindCheckbox = function(options) {
return this.each(function() {
$(this).change(function() {
if ($(this).filter(':checked').val()) {
options.checked();
} else {
options.unchecked();
}
}).trigger('change');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment