JavaScript: Detect when checkbox is ticked / unticked.

This is a JavaScript tutorial on how to detect whenever a checkbox has been ticked or unticked. In this guide, I will use both JQuery and vanilla JavaScript to detect changes to the checkbox.

Detecting checkbox changes without JQuery.

Let’s start off by looking at a vanilla JavaScript example.

Our HTML checkbox:

<input type="checkbox" id="terms" value="1" onclick="terms_change(this)" />

As you can see, we have added a function call to the inline event handler. When the user clicks on the checkbox above, the function terms_change will be called. The “this” parameter represents the checkbox itself.

In short, the DOM element will be passed in as a parameter our function, which will in turn allow us to inspect its “checked status”.

Let’s take a look at our function, which gets called after the onclick event handler is fired:

//Our custom function, which will be called whenever
//the user clicks on the checkbox in question.
function terms_change(checkbox){
    //If it is checked.
    if(checkbox.checked){
        alert('Checkbox has been ticked!');
    }
    //If it has been unchecked.
    else{
        alert('Checkbox has been unticked!');
    }
}

The JavaScript function above looks at the “checked” property of the DOM element that represents the checkbox that has been clicked on. If the property is set to TRUE, it means that the checkbox has been ticked. Similarly, if it is FALSE, then it means that the checkbox is NOT ticked.

Detect checkbox change with JQuery.

The JQuery library can help to make things a little more cleaner and concise. Firstly, we can completely remove the inline event handler from our checkbox HTML:

<input type="checkbox" id="terms" value="1" />

It is no longer needed if we are using JQuery instead of raw JavaScript.

By using the JQuery .click() method, we can capture the change like so:

$('#terms').click(function(){
    if($(this).is(':checked')){
        alert('It has been checked!');
    } else {
        alert('Our checkbox is not checked!');
    }
});

In the JavaScript example above, we captured the click event on the checkbox and then inspected its “checked” status by using JQuery’s .is() function. This function allows to test the contents of a JQuery object (in this case, the object representing our checkbox).

Note that the click event will also work if a keyboard is being used instead of a mouse. To test this out, you can tab over to the checkbox in question and then press the SPACE key.