Javascript: Check/uncheck all options for checkboxes

Here's another really simple bit of JavaScript functionality that has a real benefit to your visitors – allowing them to check or uncheck all options in a form

Checking all the boxes

To check all of the options, you can use:

<input type="button" name="Button" value="Check All" onclick="checkAll('test_form', true)" />

Or to uncheck all of the options you can use:

<input type="button" name="Button" value="Uncheck All" onclick="checkAll('test_form', false)" />

The above examples will check and uncheck all of the checkboxes that are in a form with the ID 'test_form'.

function checkAll(frm, checkedOn) {
    // have we been passed an ID
    if (typeof frm == "string") {
        frm = document.getElementById(frm);
    }

    // Get all of the inputs that are in this form
    var inputs = frm.getElementsByTagName("input");

    // for each input in the form, check if it is a checkbox
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            inputs[i].checked = checkedOn;
        }
    }
}


Comments 0

There are no comments on this yet.

Got something to say?

Join the discussion! You know how these things work; enter your details and comments below and be heard.

  1. Allowed tags: <b><i><br>