Select/Deselect All Checkboxes

by Varun Krishna P

HTML

<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>

<div id="checkboxlist">
    
    <label><input type="checkbox" name="sample[]"/> This is a checkbox1</label><br />
    <label><input type="checkbox" name="sample[]"/> This is a checkbox2</label><br />
    <label><input type="checkbox" name="sample[]"/> This is a checkbox3</label><br />
    <label><input type="checkbox" name="sample[]"/> This is a checkbox4</label><br />
    
</div>

CSS

div {
    color: #C00;
    font-family: Tahoma, Geneva, sans-serif;
    font-size: 10px;
    margin-top: 10px;
    width: 500px;
}

input {
    padding-right: 10px;
}

JavaScript

$('.selectall').click(function() {
    if ($(this).is(':checked')) {
        $('div input').attr('checked', true);
    } else {
        $('div input').attr('checked', false);
    }
});