Toggle all checkboxes present in specific div with Prototype JS

Standard

Sometimes you work with forms having a long list of checkboxes, in such scenarios a “Check All” or “Toggle Selection” button comes handy. Such button can save your time by toggling your selection with one click.

HTML:

<div id="fruits">
    <input type="button" value="Check/Uncheck All" onclick="toggle();" />

    <input type="checkbox" name="color[]" value="Red" id="red"> <label for="red">Red</label> <br />
    <input type="checkbox" name="color[]" value="Green" id="green"> <label for="green">Green</label> <br />
    <input type="checkbox" name="color[]" value="Blue" id="blue"> <label for="blue">Blue</label> <br />
    <input type="checkbox" name="color[]" value="Yellow" id="yellow"> <label for="yellow">Yellow</label> <br />
    <input type="checkbox" name="color[]" value="Black" id="black"> <label for="black">Black</label> <br />
</div>

JavaScript function:

function toggle(){
    $$('#fruits input[type=checkbox]').each(function (el) {
       el.checked = !el.checked;
    });
}

`toggle()` function will find all checkboxes inside “fruits” div and check them if not previously checked, and if they are already checked it will uncheck them due to the fact that `!el.checked` is doing negation of their current state.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: