Toggling all checkboxes with JavaScript
Update You can view the comments for alternative and quicker ways to do this, enjoy!
Say you have a list of messages, and on the left of each message is a checkbox. This checkbox is used for a mass deletion or mass insert function here. Now to make it easier on the user, its nice to add a checkbox outside of the list that either checks them all, or dechecks them all. The following function can achieve that effect, using jQuery or regular JavaScript of course.
// Javascript
function toggleCheckboxes(current, form, field) {
var val = current.checked;
var cbs = document.getElementById(form).getElementsByTagName('input');
var length = cbs.length;
for (var i=0; i < length; i++) {
if (cbs[i].name == field +'[]' && cbs[i].type == 'checkbox') {
cbs[i].checked = val;
}
}
}
// jQuery
function toggleCheckboxes(current, form, field) {
$("#"+ form +" :checkbox[name='"+ field +"[]']").attr("checked", current.checked);
}
Lets set up a quick example of how our form should be and how this function should be used properly. We will begin by adding the form tag with an id (required) and the message checkboxes.
<form action="" method="post" id="messageForm">
<input type="checkbox" name="messages[]" /> Message 1
<input type="checkbox" name="messages[]" /> Message 2
</form>
Let me explain the functions arguments before we finish up. The first argument should always be "this" so it can reference itself, the second argument would be the id of the containing form and the final argument would be the name of the checkboxes input name attribute (without the []). Now with that, we can finish this up by placing the following code anywhere on your page. Enjoy!
<label for="messages"><input type="checkbox" onclick="toggleCheckboxes(this, 'messageForm', 'messages');" /> Toggle all checkboxes</label>