Aug
2009
Assuming the markup below, determine which checkboxes are checked.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<input type="checkbox" name="cb1" id="cb1" value="a" /> A<br />
<input type="checkbox" name="cb2" id="cb2" value="b" /> B<br />
<input type="checkbox" name="cb3" id="cb3" value="c" /> C<br />
<input type="checkbox" name="cb4" id="cb4" value="d" /> D<br />
<input type="checkbox" name="cb5" id="cb5" value="e" /> E<br />
<input type="button" id="myButton" value="Which are Checked?" />
</body>
</html>
Using "POJS" (plain old JavaScript), we'd do the following (after adding an onclick attribute to the button):
<script type="text/javascript">
var checkboxes = ['cb1','cb2','cb3','cb4','cb5'];
for (var i = 0; i < checkboxes.length; i++) {
thisCheckbox = document.getElementById(checkboxes[i]);
if (thisCheckbox.checked) {
alert(thisCheckbox.value);
}
}
</script>
What we've done here is to first define an array of the "id" attributes of each checkbox. In order to access each of the checkboxes on the page, we start a loop.
On the first line inside the loop, set a variable to hold the value of the current checkbox (saves a little bit of typing). For each iteration of the loop, access the "checked" property of the current checkbox, and if it's checked, alert the value.
Not too bad. Other than having to inject the onclick attribute into our otherwise clean HTML. Not particularly crazy about having to define the array of checkbox IDs either. Potential maintenance issue as you'd need to remember to update the script if you added or removed a checkbox.
How about the jQuery way?
<script type="text/javascript">
$(function() {
$('#myButton').click(function() {
$('input:checkbox:checked').each(function(i) {
alert(this.value);
});
});
});
</script>
Using a jQuery selector ('#myButton'), I can directly access the element with that particular ID. When it's clicked, I'm going to fire the function inside the click handler.
Again, using jQuery selectors, I can access all of the checked checkboxes. Note the syntax:
$('input:checkbox:checked')
This asks jQuery to fetch all input elements that are checkboxes, but only if they're checked. If we leave off the ":checked", we get all inputs that are checkboxes. If we leave off the ":checkbox", we get all input elements (This is in contrast to the selector above that used the # symbol. This tells jQuery to get a specific element with a specific ID).
What jQuery returns from that selector is an array of elements that match the specified criteria.
jQuery provides a built-in looping mechanism, each(). This loops over each element in the resulting array from our selector. In this case, that array is going to be all checked checkboxes.
No need for conditionals within the loop to examine for a "checked" state. We've already got that. We just need to loop over it and alert the value.
For your copying and pasting pleasure, here's the template in its entirety. Because I'm referencing jQuery from Google's server, you don't need to download any additional code. It should run as-is.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#myButton').click(function() {
$('input:checkbox:checked').each(function(i) {
alert(this.value);
});
});
});
</script>
</head>
<body>
<input type="checkbox" name="cb1" id="cb1" value="a" /> A<br />
<input type="checkbox" name="cb2" id="cb2" value="b" /> B<br />
<input type="checkbox" name="cb3" id="cb3" value="c" /> C<br />
<input type="checkbox" name="cb4" id="cb4" value="d" /> D<br />
<input type="checkbox" name="cb5" id="cb5" value="e" /> E<br />
<input type="button" id="myButton" value="which are checked?" />
</body>
</html>


Comments
Add Comment | Subscribe to Comments
-
-
-
-
-
-
-
-
-
-
-
-
Add Comment# Posted Tony on 9/11/09 5:53 AM
Thanks a lot for this timely article. Just saved me some hassles today. Most other articles on this topic seems dated as their examples do not run with recent jquery downloads. Thumbs up.
# Posted madhan on 10/22/09 1:40 AM
Saved me a lot of time today thanks
# Posted Mark Llewellyn on 11/10/09 9:45 AM
I am relatively new to jQuery and in the process of refactoring a bunch of my JS code to take advantage of it. This is one of many examples of how great a tool this is! Thanks for your clear example!!
# Posted Eric Cobb on 11/17/09 12:24 PM
Perfect! This is exactly what I was looking for!
I do have one question, though. If all of the checkboxes were left unchecked, how would you display a "There are no boxes checked" message?
BTW, love the new blog theme (even though you've had it for a few months, so I guess it's not new), especially the code view!
# Posted Charlie Griefer on 11/17/09 11:05 PM
@Eric:
jQuery selectors return an array of matched elements. So on the click event of the button, you can do:
var buttonsChecked = $('input:checkbox:checked');
if (buttonsChecked.length) {
(do the code above)
} else {
alert('You did not check any buttons');
}
Give that a whirl. Let me know if it works for you.
# Posted J on 12/16/09 3:20 PM
Thanks for the example here! Do you have any problems with us copying and pasting this code into any other projects?
# Posted Charlie Griefer on 12/16/09 3:27 PM
@J - No problems. It's there for your copying-and-pasting pleasure.
# Posted auke on 1/8/10 1:26 AM
Nice job
# Posted Jeremy on 4/30/10 10:18 AM
Thanks for this example. I've been experimenting and searching high and low for the solution
for a good 6 hours finally getting it to work with your JQuery checkbox looping snippet.
Many thanks.
# Posted Ty on 7/6/10 3:31 PM
Thank You, Thank You, Thank You,
# Posted Rahul on 7/27/10 2:54 AM
Great post Charllie, I was looking for this,
Thanks for posting
# Posted jack on 8/24/10 11:59 PM
Thanks Charlie..