Decoda

Decoda is a lightweight lexical string parser for BBCode styled markup.

Toggling all checkboxes with JavaScript

Monday, July 27th 2009, 2:18am
Topics: Tutorials, Javascript, jQuery
Tags: Checkboxes, Toggle, jQuery
Comments: 6
Permalink - Tinylink

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>
Related Entries:

6 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • Bjorn Post
    bjornpost.com
    Jul 27th 2009, 06:28
    1 Inline interactions (onclick etc.) are as bad as inline styles, so you should definitely add them to the script itself. Furthermore, jQuery has an awesome function called "each", so I think it's better to use that instead of an old-skool for-loop.

    The revised code could look something like this:

    $(document).ready(function() 
    { 
        $("#checkall").click(function() // attaching the function to #checkall
        { 
            var checkedStatus = this.checked; 
            $("#form input[type=checkbox]").each(function() // looping over each checkbox inside #form.
            { 
                this.checked = checkedStatus; 
            }); 
        }); 
    });


    Of course you can transform it again into a separate function as you did in your example. :)

    Bjorn
  • Georgi Avramov
    Jul 27th 2009, 07:11
    2 Here's a much quicker/simpler way of doing it, there is also a way to avoid the passing of [this] as a parameter but I won't go into this now.

    function toggleCheckboxes(current, form, field) {
      $("#"+ form +" :checkbox[name="+field+"\\[\\]]").attr("checked", current.checked)
    }
  • Abba Bryant
    Jul 27th 2009, 08:07
    3 http://www.texotela.co.uk/code/jquery/checkboxes/
  • Brian
    mscdex.blogspot.com
    Jul 27th 2009, 12:13
    4 You can actually cut that function code down to one line only in jQuery. It's also a good idea to make the javascript unobtrusive. You could also even eliminate the toggleCheckboxes function altogether if you had a consistent structure to your forms (i.e. the checkboxes to toggle will always be adjacent to the toggling checkbox, etc). In those cases you can just use jQuery selectors to select the adjacent checkboxes of the parent form and put that one line of jQuery code in the toggle checkbox's click event code.

    However, assuming we can't be sure that will always be the case, here's what I came up with:

    Javascript:
    function toggleCheckboxes(togglebox, form, field) {
    	$("#" + form + " :checkbox[name='" + field + "[]']").attr('checked', togglebox.checked);
    }
    $(function () {
    	$("#togglebox").click(function () {
    		toggleCheckboxes(this, 'messageForm', 'messages');
    	});
    });
    


    Slightly modified HTML:
    <form action="" method="post" id="messageForm">
    	<label for="messages"><input type="checkbox" id="togglebox" /> Toggle all checkboxes</label>
    	<input type="checkbox" name="messages[]" /> Message 1
    	<input type="checkbox" name="messages[]" /> Message 2
    </form>
    
  • Miles Johnson
    milesj.me
    Jul 27th 2009, 12:51
    5 @Abba - Yes I am aware of other scripts or plugins, but why use all that when it can be done with a single function.

    @Others - Thank you guys for the alternatives :] Mine started out as a non-jQuery function, but then I just used its $ selector. Anyway would work though :P
  • Abba Bryant
    Jul 27th 2009, 16:07
    6 I figured as much, and I also expected some Jquery people (myself included within that group of course) would chime in with more "jqueryish" versions for you to look at.

    I just wanted to make sure you knew that you were reinventing the wheel and maybe point you at the most jquery'ish of the available solutions.

    I think a very simple plugin could be built around your "one function" that would make this much more useful and allow you to be more semantic with your markup. Inline javascript is evil.