Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check uncheck all CheckBoxes on the basis of another CheckBox

I want to select and unselect all checkboxes when user clicks on the first checkbox (All). And if user unchecks any checkbox, then only that checkbox and the first checkbox (All) should be unchecked and no change to the remaining checkboxes.

I have a Checkboxlist in my page which I'm populating dynamically.

<asp:CheckBoxList runat="server" ID="cbExtList" />

Code Behind

private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();

_extCollection = _extension.GetAll();

Dictionary<int, string> dExtensions = new Dictionary<int, string>();

dExtensions.Add(0, "All");
foreach (Extensions ext in _extCollection)
{
    dExtensions.Add(ext.ID, ext.Extension);
}

this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();

enter image description here

Now everything is working fine. I just want to select all Extensions when I click on the first checkbox "All" in this Checkboxlist.

This is what I tried with code behind approach.

With the OnSelectedIndexChanged and setting the AutoPostBack = True

<asp:CheckBoxList runat="server" ID="cbExtList" OnSelectedIndexChanged="cbExtList_OnSelectedIndexChanged" AutoPostBack="True" />

protected void cbExtList_OnSelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (Convert.ToInt32(this.cbExtList.SelectedItem.Value) == 0)
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = true;
            }
        }
        else
        {
            foreach (ListItem li in cbExtList.Items)
            {
                li.Selected = false;
            }
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
}
like image 261
Suhaib Janjua Avatar asked Nov 10 '22 10:11

Suhaib Janjua


1 Answers

jQuery way to do it.

This is the only jQuery code that I need to achieve the given functionality.

$(document).ready(function() {

    $('[id$=checkAllExts]').click(function () {
        $('input:checkbox').not(this).prop('checked', this.checked);
    });

    $("[id*=cbExtList_]").change(function () {
        if ($('input[id*=cbExtList_][type=checkbox]:checked').length == $('input[id*=cbExtList_][type=checkbox]').length) {
            $('[id$=checkAllExts]').prop('checked', true);
        } else {
            $('[id$=checkAllExts]').prop('checked', false);
        }
    });

});

To get IDs of the ASP.NET controls, I used the jQuery attribute selectors which is a better and simple straight way.

[name$="value"]

Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

[name*="value"]

Selects elements that have the specified attribute with a value containing a given substring.

So $('[id$=checkAllExts]') returns me the parent checkbox only on which I select/deselect all checkboxes.

And $('[id$=cbExtList_]') returns me all the checkbox except the parent checkbox and I perform my actions accordingly.

Old Answer

The Solution of checking and unchecking CheckBoxList with JavaScript on client side.

JavaScript way to do it.

<script type="text/javascript">
        var Counter;

        function ExtAll(CheckBox)
        {
            //Get target base & child control.
            var TargetBaseControl = document.getElementById('<%= this.leftCB.ClientID %>');
            var TargetChildControl = "cbExtList";

            //Get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");

            //Checked/Unchecked all the checkBoxes.
            for (var n = 0; n < Inputs.length; ++n) {
                if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
                    Inputs[n].checked = CheckBox.checked;
                //Reset Counter
            }
            Counter = CheckBox.checked ? TotalChkBx : 0;
        }

        function ChildClick(CheckBox, HCheckBox)
        {
            //get target base & child control.
            var HeaderCheckBox = document.getElementById(HCheckBox);

            //Modifiy Counter;            
            if(CheckBox.checked && Counter < TotalChkBx)
                Counter++;
            else if(Counter > 0) 
                Counter--;

            //Change state of the header CheckBox.
            if(Counter < TotalChkBx)
                HeaderCheckBox.checked = false;
            else if(Counter == TotalChkBx)
                HeaderCheckBox.checked = true;
        }
</script>

I added a checkbox before my checkboxlist to use its reference to select/unselect the checkboxlist. On that checkbox I'm calling the JavaScript function when onclick event happens.

<div id="leftCB" class="lbl" style="padding-left: 0px;" runat="server">
    <asp:CheckBox runat="server" ID="checkAllExts" Text="All" onclick="javascript:ExtAll(this);" />
    <asp:CheckBoxList runat="server" ID="cbExtList" />
</div>

Code Behind

private Extensions _extension = new Extensions();
private ExtCollection _extCollection = new ExtCollection();

_extCollection = _extension.GetAll();

Dictionary<int, string> dExtensions = new Dictionary<int, string>();

foreach (Extensions ext in _extCollection)
{
    dExtensions.Add(ext.ID, ext.Extension);

    // Added the below line for the functionality of CheckBoxList
    // which adds an attribute with all of the checkboxes in the CheckBoxList

    this.cbExtList.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');", this.checkAllExts.ClientID);
}

this.cbExtList.DataSource = dExtensions;
this.cbExtList.DataTextField = "Value";
this.cbExtList.DataValueField = "Key";
this.cbExtList.DataBind();
like image 123
Suhaib Janjua Avatar answered Nov 14 '22 22:11

Suhaib Janjua