1. Check if a single checkbox is checked
To check if a single checkbox is checked:
if ($('#' + id).is(":checked")) {
console.log("Checkbox is checked");
} else {
console.log("Checkbox is not checked");
}
2. Get all checked checkboxes with the same name
To get all checked checkboxes with the same name attribute:
var $boxes = $('input[name="thename"]:checked');
// Log the checked checkboxes
console.log($boxes);
3. Loop through the checked checkboxes
To loop through the checked checkboxes and perform actions:
$boxes.each(function() {
console.log($(this).val()); // Log the value of each checked checkbox
});
4. Find the total number of checked checkboxes
To count how many checkboxes are checked:
console.log("Number of checked checkboxes: " + $boxes.length);
Full Example
Here’s how you can combine these concepts in a complete example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkbox Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="checkboxForm">
<label><input type="checkbox" name="thename" value="Option 1"> Option 1</label><br>
<label><input type="checkbox" name="thename" value="Option 2"> Option 2</label><br>
<label><input type="checkbox" name="thename" value="Option 3"> Option 3</label><br>
<button type="button" id="checkButton">Check</button>
</form>
<script>
$('#checkButton').click(function() {
var $boxes = $('input[name="thename"]:checked');
// Loop through checked boxes and log values
$boxes.each(function() {
console.log($(this).val());
});
// Count the number of checked checkboxes
console.log("Total checked: " + $boxes.length);
});
</script>
</body>
</html>
How It Works:
- Clicking the "Check" button triggers the function.
- It gathers all checked checkboxes using
$('input[name="thename"]:checked')
. - Loops through each checked checkbox and logs its value.
- Counts and logs the total number of checked checkboxes.
This is a practical way to handle checkbox interactions in jQuery.
Top comments (0)