Explain Codes LogoExplain Codes Logo

Jquery checkbox event handling

javascript
event-handling
checkbox
jquery
Anton ShumikhinbyAnton Shumikhin·Jan 2, 2025
TLDR

When checking state changes of a checkbox in jQuery, nothing beats .on('change', handler). Here's a straight-to-the-point example:

$('#myCheckbox').on('change', function() { alert('Checkpoint 1: Checkbox now ' + (this.checked ? 'checked' : 'not checked') + '. Confirm? (y/n)'); });

Grasping the basis: handling change events

In the world of checkboxes, you often handle their change event to figure out when their state changes from checked to not checked, or vice versa. Think interactive forms, settings switches, or dynamic filters - all craving to know the state of a checkbox.

Embracing dynamicity with delegated events

Say your form likes to play dress-ups by adding checkboxes dynamically. Direct event binding would leave these newbies out. Enter delegated event handling:

$('#myDynamicForm').on('change', 'input[type="checkbox"]', function() { alert('New kid on the block: Checkbox now ' + (this.checked ? 'checked' : 'not checked') + '. Welcome it!'); });

In the above pattern, the change event of every present and future checkbox is being looked after by #myDynamicForm.

Marking off accessibility considerations

In ensuring all-use accessibility in your application, make sure your event handlers also cater to keyboard-triggered changes. Because not everyone clicks, some folks tab!

Changing via codes and triggering events

Need to change the state of a checkbox via code? Don't forget to trigger the change event. It ensures the event handlers are not left out of the party:

$('#myCheckbox').prop('checked', true).trigger('change');

How to tell if a checkbox is checked?

With jQuery, knowing whether a checkbox is checked or not is a walk in the park. Just blend the :checked selector with the .is() method. JQuery's Sizzle does the magic:

var isChecked = $('#myCheckbox').is(':checked'); console.log('Is the box checked? ' + (isChecked ? 'Yes, indeed!' : 'Nah, not yet.'));

Choosing vanilla JS for straightforward cases

Sometimes, going ditching dependencies or keeping it simple might mean no jQuery at all. Hey, onclick from vanilla JavaScript is here to the rescue:

document.querySelector('#mySimpleCheckbox').onclick = function() { console.log('Vanilla at work: Checkbox now ' + (this.checked ? 'checked' : 'unchecked') + '. Tasty, eh?'); };

This can be handy when performance is your best friend and you're counting every kilobyte of JavaScript.

Hands-on with checkbox event handling

Interactive platforms such as JSFiddle or CodePen are great for sinking your teeth into these ideas. Seeing how to handle events in a real-life demo complements these theoretical tidbits.