tags:

views:

134

answers:

3

I've got a form with a bunch of checkboxes on it, and I'd like to provide a "check all" link/button.

I'm using the code below, but when it runs, it picks up some radio buttons on the page, and checks/unchecks those too. How do I fix this?

var check = 0;
function doNow()
{
    void(d=document);
    void(el=d.getElementsByTagName('INPUT'));
    for(i=0;i<el.length;i++)
    {
        if(check == 0)
            void(el[i].checked=1)
        else
            void(el[i].checked=0) 
    }
    if(check == 0)
        check = 1;
    else 
       check = 0;
}
+7  A: 

You're going to want to check the element's type to ensure you don't accidentally go checking the wrong kind of inputs.

Basic example:

function checkAll( toggle ) {
    var inputs = document.getElementsByTagName( 'input' );
    for( var i = 0; i < inputs.length; i++ ) {
        if( inputs[i].type == 'checkbox' ) {
            inputs[i].checked = toggle;
        }
    }
}

You may want to add other checks, such as only acting on check boxes in a certain logical "group", for example.

Rob
+1  A: 

You can check the type of the input:

if(el[i].type == 'checkbox') {
   el[i].checked = true;
}
I.devries
A: 

You can store the current state as a property of the function as well as check the type

function checkAll() {
    var all = document.getElementsByTagName('input');
    for( var i = 0, l = all.length; i < l; i++ ) {
        if( all[i].type == 'checkbox' ) {
            all[i].checked = checkAll.checked;
        }
    }
    checkAll.checked = !checkAll.checked;
}
checkAll.checked = true;
meouw
Typo in your if statement. It has one = instead of 2
epascarello