Javascript Tutorials

How Do I Check If JavaScript Checkbox is Checked?

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

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago