Explain Codes LogoExplain Codes Logo

Javascript checkbox onChange

javascript
event-delegation
checkbox
event-handling
Anton ShumikhinbyAnton Shumikhin·Feb 26, 2025
TLDR

Working with a checkbox's state change in JavaScript is straightforward. Add an addEventListener to the checkbox element, listen for the 'change' event, and use this.checked to determine the checkbox's state.

document.querySelector('#checkbox').addEventListener('change', function() { // I hope you 'checked' this part, because this is where it gets interesting! console.log(`Checkbox is ${this.checked ? 'checked' : 'unchecked'}.`); });

Manage checkbox state changes

User interaction is key for any checkbox, Configure your event handler to adjust the application's business logic according to the interaction:

// This function takes care of business (logic)! function handleCheckboxChange(event) { const checkbox = event.target; if (checkbox.checked) { // If the checkbox is checked, we set the textField value to 10 setTextFieldValue(10); } else { // Else, we calculate the value based on form parameters calculateValueFromForm(); } } // Setting textField value to 10. No more, no less! function setTextFieldValue(value) { document.getElementById('textField').value = value; } // Here be dragons! A.K.A your value calculation logic function calculateValueFromForm() { // your value calculation } // Getting the checkbox element by id const checkbox = document.getElementById('myCheckbox'); // Adding event listener to handle the state change checkbox.addEventListener('change', handleCheckboxChange);

Handle dynamic forms with event delegation

When dealing with a dynamic form with multiple checkboxes, the approach taken can feel a bit like herding cats. Event delegation is here to save the day:

// Herding checkboxes like a pro with some event delegation! document.addEventListener('change', function(event) { if (event.target.type === 'checkbox') { console.log(`Checkbox ${event.target.id} is ${event.target.checked ? 'checked' : 'unchecked'}.`); } });

The jQuery way

If jQuery is your jam, toggling a checkbox is easy-peasy:

// Ride the jQuery train, no need for low-level JavaScript! $('#checkbox').change(function() { if ($(this).is(':checked')) { $('input[name="textField"]').val(10); } else { calculateValueFromForm(); } });

Key practices for readability and maintenance

To hold on to your sanity- convention over configuration:

  • In code there's a lawful good: use meaningful IDs for HTML elements.
  • Keep business logic away from event handlers. That's like mixing oil and water!
  • Always test to check if the checkbox ticked off all the expected behaviors.
  • Write clean code. Or as they say, "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."

Encode defensive caution

While rising the ranks in checkbox magic, you might stumble upon some common pitfalls:

  • Ensure your powerful calculate() function is defined and accessible. It's not a decor!
  • Be careful of synchronous and asynchronous operations. Timing is everything!
  • Cross-browser functionality: Always remember, the Internet Explorer still exists!

Accommodate all users

Don't forget to make your implementation access-friendly. More users mean more fame:

  • Don't forget to add labels for screen readers.
  • Keyboard events are best buddies with some users, remember to handle them.