【问题标题】:Check uncheck all CheckBoxes on the basis of another CheckBox在另一个 CheckBox 的基础上取消选中所有 CheckBox
【发布时间】:2014-05-05 00:03:57
【问题描述】:

当用户点击第一个复选框 (All) 时,我想选择和取消选择所有复选框。如果用户取消选中任何复选框,则只有该复选框和第一个复选框 (All) 应该被取消选中,并且不会更改其余复选框。

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

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

代码隐藏

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

现在一切正常。当我单击此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);
    }
}

【问题讨论】:

  • 您目前使用的是什么方法?如果您可以发布您现在使用的代码来尝试选中/取消选中所有复选框,这将有助于诊断您的问题
  • @PseudoNym01 我编辑了我的问题。我从后面的代码中尝试过,但没有正确实现功能。从客户端,我已经提到了我已经尝试过的链接。
  • 您使用 javascript 和 jquery 标记了问题,但据我所知,您也没有尝试使用...如果这是一个可行的选项,您可以从 jquery 轻松完成此操作
  • @Rikon,我认为如果他在客户端执行此操作,复选框的“已选择”属性将不会在服务器端更新,不是吗?
  • 我的代码可以很好地选择全部和取消选择全部。但它有一个问题,即在取消选中除第一个以外的任何复选框时,它不会取消选中它。

标签: c# javascript jquery asp.net checkbox


【解决方案1】:

遍历列表并将项目的 Selected 值设置为 true/false:

for (int i = 0; i < cbExtList.Items.Count; i++)
        {
            cbExtList.Items[i].Selected = true;
        }

【讨论】:

    【解决方案2】:

    我整理了一个示例,使用 jQuery 和 Javascript 根据第一个或 All 复选框的选中状态检查/取消选中复选框列表中的项目。

    ASPX:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>
    
        <script type="text/javascript">
            var checkedState = false;
    
            function checkAll() {
    
                $("input[id^=cblMultiple]").each(function () {
                    if ($(this).val() == 0) {
                        checkedState = $(this).is(":checked")
                    }
                    else {
                        $(this).attr("checked", checkedState)
                    }
                    //console.log(checkedState);
                    //console.log($(this).val());
                });
            }
    
            $(document).ready(function () {
                $("input[id^=cblMultiple]").each(function () {
                    if ($(this).val() == 0) {
                        $(this).on("click", checkAll);
                    }
                });
            });
    
        </script>
    </head>
    <body>
    
        <form id="form1" runat="server">
            <asp:CheckBoxList runat="server" ID="cblMultiple"/>
        </form>
    </body>
    </html>
    

    代码背后

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            cblMultiple.Items.Add(new ListItem("All", "0"));
            for (int i = 1; i < 11; i++)
            {
                cblMultiple.Items.Add(new ListItem("All" + i, i.ToString()));
            }    
        }
    }
    

    【讨论】:

      【解决方案3】:

      jQuery 方法。

      这是实现给定功能所需的唯一 jQuery 代码。

      $(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 控件的 ID,我使用了 jQuery 属性选择器,这是一种更好、更简单的直接方法。

      [name$="value"]

      选择具有指定属性且值恰好以给定字符串结尾的元素。比较区分大小写。

      [name*="value"]

      选择具有指定属性且值包含给定子字符串的元素。

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

      $('[id$=cbExtList_]') 将除父复选框之外的所有复选框都返回给我,我会相应地执行我的操作。

      旧答案

      在客户端用JavaScript勾选和取消勾选CheckBoxList的解决方案。

      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 函数。

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

      【讨论】:

        【解决方案4】:

        如果您需要在选中“全部”复选框时选中所有复选框,并在取消选中时全部取消选中,但还需要禁用每个复选框(“全部”除外)复选框当检查“所有”复选框时,此代码应该为您工作。它还具有不需要 JavaScript/jQuery 的额外好处。

        这是 .aspx 代码(对于这个场景,我有九个可以任意组合选择的设施):

        <asp:Label ID="lblFacility" AssociatedControlID="chkFacility" runat="server" Text="Facility: "></asp:Label>
        <asp:CheckBoxList ID="chkFacility" runat="server" OnSelectedIndexChanged="chkFacility_SelectedIndexChanged">
            <asp:ListItem Value="All" Text="All"></asp:ListItem>
            <asp:ListItem Value="Location1" Text="Location 1"></asp:ListItem>
            <asp:ListItem Value="Location2" Text="Location 2"></asp:ListItem>
            <asp:ListItem Value="Location3" Text="Location 3"></asp:ListItem>
            <asp:ListItem Value="Location4" Text="Location 4"></asp:ListItem>
            <asp:ListItem Value="Location5" Text="Location 5"></asp:ListItem>
            <asp:ListItem Value="Location6" Text="Location 6"></asp:ListItem>
            <asp:ListItem Value="Location7" Text="Location 7"></asp:ListItem>
            <asp:ListItem Value="Location8" Text="Location 8"></asp:ListItem>
            <asp:ListItem Value="Location9" Text="Location 9"></asp:ListItem>
        </asp:CheckBoxList>
        

        以及背后的代码:

        protected void chkFacility_SelectedIndexChanged(object sender, EventArgs e) {
            //disables all the checkboxes when "All" is selected
            if (chkFacility.SelectedIndex==0) {
                foreach(ListItem aListItem in chkFacility.Items) {
                    aListItem.Selected = true;
                    if (aListItem.Value != "All") {
                        aListItem.Enabled = false;
                    }
                }
            } else if (chkFacility.SelectedIndex > 0) {
                var i = 0;
                foreach(ListItem aListItem in chkFacility.Items) {
                    if (aListItem.Selected) {
                        i++;
                    }
                }
                //with the i++ check above, this handles unchecking every checkbox when each location is selected and the "All" checkbox is unchecked
                if (i == 9) {
                    foreach(ListItem aListItem in chkFacility.Items) {
                        aListItem.Selected = false;
                        aListItem.Enabled = true;
                    }
                //disables the "All" checkbox in all other cases where 8 or fewer of the 9 locations are selected
                } else {
                    foreach(ListItem aListItem in chkFacility.Items) {
                        if (aListItem.Value == "All") {
                            aListItem.Enabled = false;
                        }
                    }
                }
            //if no locations are selected after PostBack, make sure all checkboxes are enabled
            } else if (chkFacility.SelectedIndex == -1) {
                foreach(ListItem aListItem in chkFacility.Items) {
                    aListItem.Enabled = true;
                }
            }
        }
        

        不过,对此实现的一个警告是,如果所有位置当前都通过手动检查每个位置都被选中,则是否选择所有位置的代码也会清除选择。当我为工作编写代码时,这种边缘情况是可以接受的风险,因为它不太可能并且考虑到如果需要选择所有位置,无论如何用户都应该选中“全部”复选框。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-05
          • 1970-01-01
          • 2012-03-18
          • 1970-01-01
          • 2019-02-14
          • 1970-01-01
          • 2011-10-02
          相关资源
          最近更新 更多