How to Call a JavaScript Function When a Checkbox is Checked or Unchecked

As a developer working on a project where I needed to trigger certain actions whenever users interacted with checkboxes on my web page. The issue is, many developers struggle with implementing this functionality efficiently.

In this tutorial, I will cover several simple ways you can use to call JavaScript functions when a checkbox is checked or unchecked (one using event listeners and one using inline events).

So let’s get started..

Method 1 – Use Event Listeners in JavaScript

Event listeners are the modern, recommended way to handle checkbox changes. They keep your HTML clean and your JavaScript organized.

Below, I have a simple checkbox that I want to monitor for changes:

<input type="checkbox" id="termsCheckbox" class="terms-checkbox">
<label for="termsCheckbox">I agree to the terms and conditions</label>
<div id="message"></div>

You can refer to the screenshot below to see the output.

Call a JavaScript Function When a Checkbox is Checked or Unchecked

Here are the steps to call a function when this checkbox is checked or unchecked:

  1. First, select the checkbox element using JavaScript.
  2. Add an event listener for the ‘change’ event.
  3. Write the function that will run when the checkbox state changes.
// Select the checkbox
const checkbox = document.getElementById('termsCheckbox');
const messageDiv = document.getElementById('message');

// Add event listener
checkbox.addEventListener('change', function() {
    if(this.checked) {
        messageDiv.textContent = "Thank you for agreeing to our terms!";
        messageDiv.style.color = "green";
        // Call any other functions you need here
        enableSubmitButton();
    } else {
        messageDiv.textContent = "Please accept the terms to continue.";
        messageDiv.style.color = "red";
        // Call any other functions you need here
        disableSubmitButton();
    }
});

function enableSubmitButton() {
    // Code to enable a submit button
    const submitButton = document.getElementById('submitButton');
    if(submitButton) submitButton.disabled = false;
}

function disableSubmitButton() {
    // Code to disable a submit button
    const submitButton = document.getElementById('submitButton');
    if(submitButton) submitButton.disabled = true;
}

You can refer to the screenshot below to see the output.

How to Call a JavaScript Function When a Checkbox is Checked or Unchecked

This approach is clean and follows modern JavaScript practices. The event listener waits for any change to the checkbox and then runs the function you’ve defined.

Read Expandable Table with Collapsible Rows Using HTML, CSS, and JavaScript

Method 2 – Use Inline Event Handlers

While not the most modern approach, inline event handlers can be useful for simple applications or quick prototypes.

<input type="checkbox" id="newsletterCheckbox" onchange="handleNewsletterSignup(this)">
<label for="newsletterCheckbox">Subscribe to our newsletter</label>
<div id="newsletterMessage"></div>

<script>
function handleNewsletterSignup(checkbox) {
    const messageDiv = document.getElementById('newsletterMessage');

    if(checkbox.checked) {
        messageDiv.textContent = "You've subscribed to our newsletter!";
        messageDiv.style.color = "blue";
        // Add email to newsletter list or other actions
        saveEmailPreference(true);
    } else {
        messageDiv.textContent = "You've unsubscribed from our newsletter.";
        messageDiv.style.color = "gray";
        // Remove email from newsletter list or other actions
        saveEmailPreference(false);
    }
}

function saveEmailPreference(isSubscribed) {
    // Code to save user preference
    console.log(`Newsletter preference set to: ${isSubscribed}`);
    // In a real application, you might send this to your server
}
</script>

You can refer to the screenshot below to see the output.

Call JavaScript Function When a Checkbox is Checked or Unchecked

The advantage here is simplicity, the HTML directly tells you what happens when the checkbox changes. However, this approach mixes HTML and JavaScript, which isn’t ideal for larger applications.

Method 3 – Use jQuery for Checkbox Events

If you’re working with jQuery in your project, handling checkbox events becomes even simpler.

<input type="checkbox" id="darkModeToggle" class="theme-toggle">
<label for="darkModeToggle">Enable Dark Mode</label>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('#darkModeToggle').change(function() {
        if($(this).is(':checked')) {
            enableDarkMode();
        } else {
            disableDarkMode();
        }
    });
});

function enableDarkMode() {
    $('body').addClass('dark-theme');
    $('body').removeClass('light-theme');
    console.log("Dark mode enabled");
    // Save user preference
    localStorage.setItem('theme', 'dark');
}

function disableDarkMode() {
    $('body').addClass('light-theme');
    $('body').removeClass('dark-theme');
    console.log("Dark mode disabled");
    // Save user preference
    localStorage.setItem('theme', 'light');
}
</script>

jQuery’s .change() method makes it easy to attach event handlers. This is especially useful if you’re already using jQuery in your project.

Method 4 – Handle Multiple Checkboxes with a Single Function

When you have multiple checkboxes that need similar handling, you can use a common class and a single event handler:

<div class="preferences">
    <div>
        <input type="checkbox" id="preference1" class="preference-checkbox" data-preference="emails">
        <label for="preference1">Receive promotional emails</label>
    </div>
    <div>
        <input type="checkbox" id="preference2" class="preference-checkbox" data-preference="sms">
        <label for="preference2">Receive SMS notifications</label>
    </div>
    <div>
        <input type="checkbox" id="preference3" class="preference-checkbox" data-preference="calls">
        <label for="preference3">Receive phone calls</label>
    </div>
</div>

<script>
// Select all checkboxes with the common class
const preferenceCheckboxes = document.querySelectorAll('.preference-checkbox');

// Add event listener to each checkbox
preferenceCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', handlePreferenceChange);
});

function handlePreferenceChange(event) {
    const checkbox = event.target;
    const preferenceType = checkbox.dataset.preference;
    const isChecked = checkbox.checked;

    console.log(`Preference ${preferenceType} is now ${isChecked ? 'enabled' : 'disabled'}`);

    // Save the user preference
    saveUserPreference(preferenceType, isChecked);

    // You could also update UI elements based on the change
    updatePreferenceUI(preferenceType, isChecked);
}

function saveUserPreference(preference, value) {
    // In a real application, this might send data to a server
    console.log(`Saving preference: ${preference} = ${value}`);
    // Example: localStorage.setItem(`pref_${preference}`, value);
}

function updatePreferenceUI(preference, enabled) {
    // Update other UI elements based on the preference change
    // For example, show/hide related options
    const relatedElements = document.querySelectorAll(`.${preference}-options`);
    relatedElements.forEach(el => {
        el.style.display = enabled ? 'block' : 'none';
    });
}
</script>

This approach is very scalable; you can add more checkboxes with the same class, and they’ll automatically be handled by your function. The data attributes help you identify which specific checkbox was changed.

Both methods work great – the event listener approach is cleaner and more maintainable for larger projects, while inline handlers offer simplicity for small applications. The jQuery method is perfect if you’re already using jQuery, and the multiple checkbox handler is ideal when you need to process several similar checkboxes.

I hope you found this article helpful. If you have any questions or suggestions, kindly leave them in the comments below.

Other articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.