选中取消选中基于另一个CheckBox的所有CheckBox [英] Check uncheck all CheckBoxes on the basis of another CheckBox

查看:68
本文介绍了选中取消选中基于另一个CheckBox的所有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.

我的页面中有一个 Checkboxlist ,我正在动态填充。

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();

现在一切正常。我只想在点击此复选框中的第一个复选框全部时选择所有扩展程序。

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

这是我尝试使用代码隐藏方法。

使用 OnSelectedIndexChanged 并设置 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);
    }
}


推荐答案

已编辑



JQuery的做法。

这是唯一的 JQuery 我需要实现给定功能的代码。

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);
        }
    });

});

获取 ASP.NET 的I​​D控件,
我使用 JQuery 属性选择器,这是一种更好,更简单的直接方式。

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.

所以 $('[id $ = checkAllExts]')只返回我选中/取消选中所有复选框的父复选框。

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

$('[id $ = cbExtList _]')返回除了父复选框以外的所有复选框,并相应地执行我的操作。

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

在客户端使用JavaScript检查和取消选中 CheckBoxList 的解决方案。

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

JavaScript方式。

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

我在复选框列表前添加了一个复选框,以使用其参考来选择/取消选择复选框列表。
在该复选框上,当 onclick 事件发生时,我正在调用javascript函数。

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>

代码背后

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();

这篇关于选中取消选中基于另一个CheckBox的所有CheckBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆