31
Select all checkboxes using jQuery
Entry Feed TrackbackIf you ever need to select all checkboxes in a form this tutorial will show you how to do it. This is useful when a user needs to delete all data in his control panel (emails, friends, articles etc.).
All we need is a JavaScript function called ToggleCheck and jQuery framework.
You can download the latest jQuery here.
ToggleCheck function (save this in your script.js file):
function ToggleCheck(id, sel){
jQuery('input[type=checkbox][id='+id+']').each(function(i){
if(jQuery(sel).attr('checked')){
jQuery(this).attr('checked','checked');
}
else {
jQuery(this).attr('checked','');
}
});
}
Insert the script tags in your html file :
<script language="javascript" type="text/javascript" src="path/to/jquery.js"></script> <script language="javascript" type="text/javascript" src="path/to/script.js"></script>
Now we can use the script :
<form action=”" method=”post”>
<label><input type=”checkbox” onchange=”ToggleCheck(’check’,this)” /> Check / Uncheck all</label><br />
<label><input type=”checkbox” name=”somename” id=”check” value=”val 1″ /> Value 1</label><br />
<label><input type=”checkbox” name=”somename” id=”check” value=”val 2″ /> Value 2</label><br />
<label><input type=”checkbox” name=”somename” id=”check” value=”val 3″ /> Value 3</label><br />
<label><input type=”checkbox” name=”somename” id=”check” value=”val 4″ /> Value 4</label><br />
</form>
Enjoy!


Tried the demo… does not work
rupa at Mar 6, 09 at 12:44 am
what browser did you tested in?
admin at Mar 6, 09 at 9:03 am
Just what I was looking for - thanks for an easy, clear, simple example!
David at Apr 9, 09 at 12:39 pm
Why you used
onchange=”ToggleCheck(’check’,this)” on the html code? It’s a strange behaviour using jquery
Galawyn at May 2, 09 at 9:43 am
this is an old script. i will update the script soon.
also it generates invalid html code bacause i used the same id for all checkboxes
admin at May 2, 09 at 11:59 am