Home >>Javascript Programs >Check/Uncheck all Checkboxes on Button Click using JavaScript

Check/Uncheck all Checkboxes on Button Click using JavaScript

Check/Uncheck all Checkboxes on Button Click using JavaScript

In this article, we will learn how to code select/Unselect (check/uncheck) all Checkboxes on Button Click by using JavaScript.

This JavaScript function is used to check (select), unselect (uncheck) all checkboxes by just clicking one button. By using this code we will check or uncheck all checkboxes in one click.

Method

  • You need to create a JavaScript function.
  • Use window.onload function : you can use this function as soon as the page refresh or loading.
  • Use window.addEventListener: It helps you to adding event listeners on any HTML document that support events.

So, this article is helpful how to check/Uncheck all checkboxes on Button Click.

Let's take an example:

<html>
	<head>
		<title>JavaScript - Select/Unselect (Check/Uncheck) all CheckBoxes on Button Click.</title>
		<script type="text/javascript">
			function selectAll(){
				var items=document.getElementsByName('acs');
				for(var i=0; i<items.length; i++){
					if(items[i].type=='checkbox')
						items[i].checked=true;
				}
			}
			function UnSelectAll(){
				var items=document.getElementsByName('acs');
				for(var i=0; i<items.length; i++){
					if(items[i].type=='checkbox')
						items[i].checked=false;
				}
			}			
		</script>
	</head>
<body>
	<input type="checkbox" name="acs" value="Red">Red<br>
	<input type="checkbox" name="acs" value="Blue">Blue<br>
	<input type="checkbox" name="acs" value="Yellow">Yellow<br>
	<input type="checkbox" name="acs" value="Orange">Orange<br>
	<input type="checkbox" name="acs" value="Pink">Pink<br>
	<input type="checkbox" name="acs" value="Voilet">Voilet<br>
	<p>
	<input type="button" onclick='selectAll()' value="Select All"/>
	<input type="button" onclick='UnSelectAll()' value="Unselect All"/>
	</p>
</body>
</html>
Output:

 

Red
Blue
Yellow
Orange
Pink
Voilet


No Sidebar ads