In this tutorial we will see how to Count Checked Checkboxes of Specific Form with JavaScript. The document.forms property, JavaScript length property and querySelectorAll() Method are used for this.
Table of Contents
HTML Code
HTML Code is given below, This code contains HTML form with three label elements for three checkbox type input elements. HTML button is used to execute JavaScript function on onclick event to count the number of checked checkboxes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Count Checked Checkboxes of Specific Form with JavaScript</title>
</head>
<body>
<form name="main">
<label>HTML</label>
<input type="checkbox">
<label>CSS</label>
<input type="checkbox">
<label>JAVASCRIPT</label>
<input type="checkbox">
</form>
<button onclick="countCheckboxes()">Count Checkboxes</button>
</body>
</html>
document.forms property
The document.forms is read-only HTML Dom Property which returns the list of all forms that are available on the HTML page or document.
You can use document.forms property to get an element inside selected HTML form. Or you can use this property to target a specific HTML form with a specific name.
HTML form name is defined using the name attribute.
JavaScript length property
The JavaScript length property returns the length of the string.
JavaScript length property is used to count the number of selected HTML elements.
querySelectorAll() Method
The querySelectorAll() Method is used to select or target all HTML elements that matches with specified CSS Selector.
The querySelectorAll() Method will return a list of all HTML elements which match the specified group of selectors.
JavaScript Code
In this example a main function "countCheckboxes()" will be executed on onclick event.
Then the document.forms property will return the only HTML form available on the page with name "main".
Then querySelectorAll method will return the list of checkbox type input elements which are checked. This will be done using input[type="checkbox"]:checked CSS Selector.
Then finally .length property will be used to count the number of checked checkboxes.
This number is then displayed using alert method.
The good thing about this code is that this will only count checked checkboxes of a specific html form on current page, not all forms.
Take a look at the code given below.
<script>
function countCheckboxes(){
var a = document.forms["main"];
var x =a.querySelectorAll('input[type="checkbox"]:checked');
alert(x.length);
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Count Checked Checkboxes of Specific Form with JavaScript.