How Do I Check If JavaScript Checkbox is Checked?

Article By Digamber Rawat on

How to Manage Checkboxes OnClick in JavaScript?

I am going to show you how can you handle on click event in JavaScript for checking if checkboxes and groups of checkboxes are checked.

Let’s start binding click event to checkbox using JavaScript. To attach an onclick event to the checkbox, we need to get the reference of the HTML checkbox element using the ID, and then we bind it to JavaScript function.

HTML

<input type="checkbox" id="agree" value="I am Agree!"> Do you agree?

JavaScript

// Bind function to onclick event for checkbox
document.getElementById('agree').onclick = function() {
    // access properties using this keyword
    if ( this.checked ) {
        // Returns true if checked
        alert( this.value );
    } else {
        // Returns false if not checked
    }
};

JavaScript Check If Checkbox is Checked Demo

With the help of onClick event, JavaScript function and this keyword, we can pretty easily check If the checkbox is checked. It also allows us to add any condition we want within our if and else statement

JavaScript Multiple Checkboxes Onclick Example

In the below example we are going to manage the multiple checkboxes Onclick example using the JavaScript.

Checkbox Group HTML Form

I am going to create a basic HTML form, i will be creating a beauty product selection kit in JavaScript. Basically a user can customize beauty products kit, we are going to take help of checkboxes to add or remove beauty products in users make up kit. Below form will give you an idea about our functionality.

<form>
<fieldset>
<legend>Checkboxes Group Demo</legend>
<p>Makeup Kit Basic => <strong>$60.00</strong></p>
<div id="beautyProducts">Add On =>
<label><input type="checkbox" name="lipstick" value="15" /> Lipstick</label>
<label><input type="checkbox" name="eyeliner" value="16" /> Eyeliner</label>
<label><input type="checkbox" name="brushes" value="12" /> Brushes</label>
<label><input type="checkbox" name="concealer" value="18" /> Concealer</label>
</div>
<p class="total-cost">
<label>Total Cost: $ <input type="text" name="total-cost" class="total-cost" value="60.00" readonly="readonly" /></label>
</p>
</fieldset>
</form>

Checkboxes Group in JavaScript

In this part of the tutorial, I am going to show you how you can work on checkboxes group in JavaScript. In the demo, you can select, and unselect any products from the beauty products list using the HTML checkboxes.

Now let’s understand how we’ve achieved this functionality in JavaScript.
We have wrapped all the checkboxes within a div container using ‘beautyProducts’ ID. Every input has been assigned some price, in the form below we have total cost section. Here we will show the total cost of the makeup kit depending on what products users select.

There are 2 functions in our checkbox grouping logic calculateCheckbox() and updateCost().

Let’s find out what is going on in calculateCheckbox() function.
In this function, I am getting the beauty products checkboxes container’s reference along with product input element reference from beauty products container and using for loop to iterate over every checkbox item in a group. Within the for loop, I am calling updateCost() function on every click.

Now let’s check out the critical role of updateCost() function.
This function is doing the calculation for us, and most importantly we are checking here if the checkboxes are checked using the JavaScript if else condition.

function calculateCheckbox() {
// get beauty products checkboxes contianer's reference
var el = document.getElementById('beautyProducts');
// get beauty product input element reference in beauty products container
var products = el.getElementsByTagName('input');
// get products length
var len = products.length;
// call updateCost() function to onclick event on every checkbox
for (var i = 0; i < len; i++) {
if (products[i].type === 'checkbox') {
products[i].onclick = updateCost;
}
}
}
// called onclick of beauty products checkboxes
function updateCost(e) {
// 'this' reffered to checkbox clicked on
var myForm = this.form;
// include current value in total-cost block, use parseFloat method to convert string to number
var val = parseFloat(myForm.elements['total-cost'].value);
// Add the checkbox value to total value if checkbox is checked
if (this.checked) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
// update total-cost value with latest value
myForm.elements['total-cost'].value = val
}
// call calculateCheckbox method
calculateCheckbox();

JavaScript Checkbox Group Preview

Digamber Rawat

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me