Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check/Uncheck checkboxes on select of a master checkbox in jquery

I have a checkboc in my column header. Onclick of it, all the checkboxes needs to be checked and on uncheck of master checkbox all should be unchecked. I googled a lot but I got only javascript code for this kind of thing. But I want pure JQuery thing.I am pasting my code here. Now onclick of master checkbox, all the checkboxes are checking but master checkbox itself Can somebody help me with jquery code.

This is my header checkbox:

<input type="checkbox" onclick="checkBoxChecked()" id="mastercheck" name ="mastercheck"/>

Onclick method is

function checkBoxChecked(){
         try{

        var checkboxes=document.getElementsByName("test");

        for(i=0;i<document.getElementsByName("test").length;i++)
        {
         checkboxes[i].checked = "checked";
        }

        }
        catch(e)
        {

        }

        document.getElementById("mastercheck").checked="checked";
        return true;

        }
like image 520
Sanjay Malhotra Avatar asked Dec 01 '22 18:12

Sanjay Malhotra


1 Answers

HTML:

<input type="checkbox" id="ckbCheckAll" />
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />
    </p>

JQuery:

$(document).ready(function () {
    $("#ckbCheckAll").click(function () {
        $(".checkBoxClass").prop('checked', $(this).prop('checked'));
    });
});

Live Demo

like image 64
NaYaN Avatar answered Dec 10 '22 13:12

NaYaN