Javascript function to check and uncheck all checkboxes.

Posted by Damodar Bashyal on April 21, 2012

 

Today I was filling one online form with 100 plus checkboxes, after checking 4-5 boxes, felt bored. So, wrote a simple javascript function and ran it through firefox's firebug console and checked all boxes with just one click on run.

I had a simple one with no if conditions, but decided to make it better so i could use it on my websites. So here you go, a very simple JS check and uncheck all checkboxes functions. Just one function handles both options.

/*
 * frm = Name of the form
 * fname = Unique name of the checkboxes
 * check = set checkbox checked or unchecked (true|false)
 */

function setCheckBoxes(frm, fname, check){
    var frm = document.forms[frm];
    if(frm == 'undefined'){
        return;
    }

    var chkBoxs = frm.elements[fname];
    if(chkBoxs == 'undefined'){
        return;
    }

    for($k in chkBoxs){
       chkBoxs[$k].checked = check;
    }
}
//setCheckBoxes('installfrm', 'toinstall[]', true); //sets as checked
//setCheckBoxes('installfrm', 'toinstall[]', false); //sets as unchecked

Checkbox name can be array or just simple name. Both are supported.

To check or uncheck all checkboxes:

<a href="javascript:setCheckBoxes('installfrm', 'toinstall[]', true);">Check all</a>
<a href="javascript:setCheckBoxes('installfrm', 'toinstall[]', false);">Uncheck all</a>
 
not published on website


QR Code: Javascript function to check and uncheck all checkboxes.