The checkbox is very useful to get multiple values. By default, the selected checkboxes value is posted on form submission to the server-side. But if you want to get the selected checkboxes values without form submission, jQuery is the best option. The selected checkboxes value can be get easily using jQuery. In the example code snippet, we will show you how to get all the selected checkboxes value using jQuery.
The following code will help you to get values of all checked checkboxes by class name using jQuery.
In the following HTML, the chk
class is tagged to each checkbox. Also, a button is placed under the checkboxes, that trigger the jQuery code to get the values of all selected checkboxes.
<!-- checkboxes -->
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>
<!-- button to get values -->
<input type="button" id="getValue" value="Get Selected Checkboxes Value">
Include the jQuery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The following jQuery code gets the selected checkboxes value. If selected, checked checkboxes values are shown, otherwise, an alert appears.
$(document).ready(function(){
$('#getValue').on('click', function(){
// Declare a checkbox array
var chkArray = [];
// Look for all checkboxes that have a specific class and was checked
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
// Join the array separated by the comma
var selected;
selected = chkArray.join(',') ;
// Check if there are selected checkboxes
if(selected.length > 0){
alert("Selected checkboxes value: " + selected);
}else{
alert("Please select at least one checkbox.");
}
});
});