In this article we'll look at some ways to programmatically toggle a checkbox using JavaScript. Let's consider we have the following checkbox element:
<input type="checkbox" id="toggle-me" />
But before we can toggle the checkbox, we first need to select it. Let's, for example, select it by its id like so:
const checkbox = document.getElementById('toggle-me');
#Toggle Checkbox by Using Inverse of Checkbox checked
Property
By simply using the logical NOT operator (!
) we can get the inverse value of checkbox.checked
. If we assign that to the checked
property of the checkbox input field, we can toggle the checkbox. For example:
checkbox.checked = !checkbox.checked;
#Toggle Checkbox Using the Bitwise XOR Operator
Although, the XOR operator may not appear very readable, it is very easy to understand. It is denoted by the caret symbol (^
), and evaluates to the following:
a | b | a ^ b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
With that information, you can deduce that a ^ b
evaluates to true
when a
and b
have different values, and false
when they have the same values. Therefore, we can simply do:
checkbox.checked = checkbox.checked ^ 1;
Or (preferably) use the shorthand equivalent:
checkbox.checked ^= 1;
If you follow the results of the bitwise XOR operations, it might help you understand the following table (which illustrates the way toggling the checkbox checked
value works with the XOR operator):
checkbox.checked | 1 | checkbox.checked ^ 1 |
---|---|---|
false |
true |
true |
true |
true |
false |
#Toggle Checkbox by Simulating a Mouse Click
By using the click()
method on the checkbox we can simulate a mouse click, which would flip the checkbox value. For example:
checkbox.click();
Please note that this would fire the checkbox's click event, and bubble up to elements higher in the document tree (or event chain) and fire their click events as well.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.