Toggle All Checkboxes

By Hawkee on Oct 18, 2008

This is a simple Javascript snippet that lets you toggle a group of checkboxes on or off at the same time. This is the format for your HTML form:

<input type=checkbox id='toggleall' onClick="toggleAll('myform');"> Toggle All

<input type=checkbox id='myform1'>
<input type=checkbox id='myform2'>
<input type=checkbox id='myform3'>

You can use this in multiple groups on the same page or form. Groups are determined by the checkbox id's which need to match followed by 1, 2, 3..

function toggleAll(id) {
    box = document.getElementById(id);

    if(box.checked == true) var setting = true;
    else var setting = false;

    var cur_id = id+'1';

    var count = 1;
    while(box = document.getElementById(cur_id)) {
        box.checked = setting;
        cur_id = id+count;
        count++;
    }
}

Comments

Sign in to comment.
Korvin   -  Mar 02, 2010

for loops my friend.

for(count = 1;box = document.getElementById(cur_id);count++)
    {
        box.checked = setting;
        cur_id = id+count;
    }

also, jquery.

function toggleAll(id) { $("[id^="+id+"]:checkbox").attr('checked', true);}

same sht as yours.

 Respond  
napalm`   -  Oct 19, 2008

Looks handy.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.