A simple way to get all selected checkbox values in an array using jQuery

By | May 26, 2021

If you are creating a form where you need your users to check one or more check-boxes so that you can get their answers, and you might be figuring out a way to get all selected checkbox values in an array using jQuery code, so that you can process the user inputs/answers as you wish.

So, in this how to guide, we will go step by step to understand how we can get all selected checkbox values in an array:

Steps:

  • First, we will select all the selected checkboxes using jQuery :checked Selector. Now, we know the check-boxes which the user has checked in the form.
  • Now we will loop through each selected checkbox using jQuery .each() loop method and at the same time, we will be storing values in the array.

Here is the jQuery code:

var usersInterest = [];
	$(function() {
	    $('#click_button').click(function(e){
		  $("input:checkbox[name=your_interest]:checked").each(function(){
				usersInterest.push($(this).val());
		  });
		  alert(usersInterest); // 
		});
	});

The Complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Simple ways to get all selected checkbox value in an array using jQuery</title>
  <style>
	#parent_div{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
  </style>
</head>
<body>
	<div id="parent_div">
	<h3>You are interested in:</h3>
	<label>
		JavaScript: <input type="checkbox" name="your_interest" value="JavaScript" />
	</label>
	<br />
	<label>
		 jQuery: <input type="checkbox" name="your_interest" value="jQuery" />
	</label>
	<br />
	<label>
		 NodeJs: <input type="checkbox" name="your_interest" value="NodeJs" />
	</label>
	<br />
	<label>
		ReactJs: <input type="checkbox" name="your_interest" value="ReactJs" /> 
	</label>
	<br />
		<input type="button" id="click_button" value="Submit" />
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
    var usersInterest = [];
	$(function() {
	    $('#click_button').click(function(e){
		  $("input:checkbox[name=your_interest]:checked").each(function(){
				usersInterest.push($(this).val());
		  });
		  alert(usersInterest); // 
		});
	});
  </script>
</body>
</html>