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
}
};
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
In the below example we are going to manage the multiple checkboxes Onclick example using the JavaScript.
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>
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();
In this post, we will learn how to work with HTTP requests in the Redux…
MySQL is a relational database management system based on SQL – Structured Query Language, and…
React Js Handle Rest API data globally with Context and useState hook tutorial. In this…
Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…
In this tutorial, you will discover how to import CSV file into MySQL database using…
React Js Global state management with createContext hook example; In this tutorial, we will help…