Toggle checkboxes with jQuery and Prototype JS

Toggle checkboxes with jQuery and Prototype JS

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="toggleCheckboxes();" />

    <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>

Toggle checkboxes with Prototype Js

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

jQuery function:

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

`toggleCheckboxes()` 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.

Author: Tahir Yasin

Tahir is a Passionate Web Developer from Lahore, Pakistan and a guy with NEVER-STOP-LEARNING attitude who keeps an eye on emerging technologies and customer trends.

Leave a Reply

Your email address will not be published. Required fields are marked *