【问题标题】:How can I implement a "Select All" checkbox in my ASP.NET MVC app?如何在我的 ASP.NET MVC 应用程序中实现“全选”复选框?
【发布时间】:2010-11-15 21:08:59
【问题描述】:

我有一个表格,其中有一列充满了复选框。在顶部,我希望有一个“全选”复选框来检查该页面上的所有复选框。

我应该如何实现这个?如果重要的话,我会使用 jQuery 作为我的 JavaScript 框架。

【问题讨论】:

    标签: jquery asp.net-mvc checkbox


    【解决方案1】:

    这将使所有单独的复选框与“全部选中”的复选框相同

    $("#id-of-checkall-checkbox").click(function() {
        $(".class-on-my-checkboxes").attr('checked', this.checked);
    });
    

    这将使“全选”与各个复选框实际上是否都被选中保持同步

    $(".class-on-my-checkboxes").click(function() {
        if (!this.checked) {
            $("#id-of-checkall-checkbox").attr('checked', false);
        }
        else if ($(".class-on-my-checkboxes").length == $(".class-on-my-checkboxes:checked").length) {
            $("#id-of-checkall-checkbox").attr('checked', true);
        }
    });
    

    【讨论】:

    • 这看起来像是 else if case 不起作用...当所有子复选框都被选中时,它应该将 checkall 复选框设置为 true。有什么想法吗?
    • 我想我想通了...在 ":checked" 之前添加了一个空格并且它起作用了。
    【解决方案2】:

    jquery(EDITED 切换选中/取消选中全部):

    $(document).ready(function() {
        $("#toggleAll").click(function() {  
          $("#chex :checkbox").attr("checked", $(this).attr("checked"));
        });    
    });
    

    我必须执行click() 然后检查checked 状态的原因是,如果您尝试“toggle”复选框,则被切换的复选框将不会保持其选中状态。这样它可以保留检查状态并有效地切换。

    HTML:

    <input type="checkbox" id="toggleAll" />
    <div id="chex">
        <input type="checkbox" />
        <input type="checkbox" />
        <input type="checkbox" />
        <input type="checkbox" />
    </div>
    

    【讨论】:

    • 那些看起来像 ASP.NET 复选框,而不是 ASP.NET-MVC。 MVC 只会使用常规的 html 复选框。这会如何改变事情?
    • 使用此解决方案,如果用户取消选中“全选”复选框,则复选框将保持选中状态。请参阅下面的 jQuery 回答来处理选择和取消选择所有框。
    • @kingnestor - 它不会改变任何东西。使用您的标准复选框,这将起作用。
    • 您应该创建一个基于表格标记的示例,其中全选复选框出现在标题行中。当前示例标记与问题中列出的完全不同。
    • 另外,您正在使用“段落”进行切换,而 OP 想要一个复选框来切换状态。
    【解决方案3】:

    对我来说,Jeremy 的解决方案最有效,但我不得不用.prop 替换 .attr。否则,一旦我单击一个复选框,它就会停止对“主”复选框做出反应。

    在 _Layout.cshtml(母版页)中

    $(document).ready(
        manageCheckboxGroup('chkAffectCheckboxGroup', 'checkbox-group')
    );
    

    在引用的 .js 中

        function manageCheckboxGroup(masterCheckboxId, slaveCheckboxesClass) {
    
        $("#" + masterCheckboxId).click(function () {
            $("." + slaveCheckboxesClass).prop('checked', this.checked);
        });
    
        $("." + slaveCheckboxesClass).click(function () {
            if (!this.checked) {
                $("#" + masterCheckboxId).prop('checked', false);
            }
            else if ($("." + slaveCheckboxesClass).length == $("." + slaveCheckboxesClass + ":checked").length) {
                $("#" + masterCheckboxId).prop('checked', true);
            }
        });
    }
    

    在 HTML(Razor)页面中

    <table class="table">
        <thead>
            <tr>
                <th><input id="chkAffectCheckboxGroup" type="checkbox" checked="checked" /></th>
                <th>
                    @Html.DisplayNameFor(model => model.Clients[0].ClientId)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Clients[0].Name)
                </th>
            </tr>
        </thead>
        <tbody>
            @for (int i = 0; i < Model.Clients.Count(); i++)
            {
                <tr>
                    <td>
                        <input type="hidden" asp-for="Clients[i].Id" class="form-control" />
                        <input type="hidden" asp-for="Clients[i].Name" />
                        <input type="checkbox" class="checkbox-group" asp-for="Clients[i].Selected" />
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => Model.Clients[i].Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => Model.Clients[i].Name)
                    </td>
                </tr>
            }
        </tbody>
    </table>
    

    重要提示: 另外,起初我在 HTML 中有一个 @foreach 循环,但它不起作用......,您必须使用 @for (int i = 0; i &lt; Model.Clients.Count(); i++) 循环,否则您最终会在 OnPostAsync() 中得到一个空列表。

    【讨论】:

      【解决方案4】:

      根据 Marve 的回答稍微修改标记(将 ID 提供给表格)

      Working Demo →

      编辑:

      “selectAll”复选框正确反映复选框状态的更新版本。例如。如果您手动选择所有复选框,则 selectAll 复选框将自动被选中。尝试演示以了解行为。

      代码:

      <table id='myTable'>
          <thead>
              <tr>
                  <th><input type="checkbox" /></th>
                  <th>Column 1</th>
                  <th>Column 2</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td><input type="checkbox" /></td>
                  <td>Tabular Data 1</td>
                  <td>Tabular Data 2</td>
              </tr>
              <tr>
                  <td><input type="checkbox" /></td>
                  <td>Tabular Data 3</td>
                  <td>Tabular Data 4</td>
              </tr>
          </tbody>
      </table>
      

      你的 jQuery 可以这么简单:

      $(document).ready(
          function()
          {
              $('#myTable th input:checkbox').click(
                  function() 
                  {
                      $('#myTable td input:checkbox').attr('checked', $(this).attr('checked'));
                  }
              );
      
              //The following code keeps the 'selectAll' checkbox in sync with
              //the manual selection of the checkboxes by user. This is an additional usability feature.
              $('#myTable tr input:checkbox').click(
                  function()
                  {
                      var checkedCount = $('#myTable td input:checkbox:checked').length;
                      var totalCount = $('#myTable td input:checkbox').length;
                      $('#myTable th input:checkbox').attr('checked', checkedCount === totalCount);
                  }
              );
          }
       );
      

      【讨论】:

      • 和我上面的评论一样...这对我不起作用,直到我在 ":checked" 选择器前放了一个空格。
      【解决方案5】:

      虽然之前发布的答案有效,但如果您在单个页面中有多个复选框,则会遇到问题。

      无论如何,这种格式都可以使用:

      <table>
          <thead>
              <tr>
                  <th><input type="checkbox" /></th>
                  <th>Column 1</th>
                  <th>Column 2</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td><input type="checkbox" /></td>
                  <td>Tabular Data 1</td>
                  <td>Tabular Data 2</td>
              </tr>
              <tr>
                  <td><input type="checkbox" /></td>
                  <td>Tabular Data 3</td>
                  <td>Tabular Data 4</td>
              </tr>
          </tbody>
      </table>
      

      还有脚本...

      $(function() {
          $('th > :checkbox').click(function() {
              $(this).closest('table')
                  .find('td > :checkbox')
                  .attr('checked', $(this).is(':checked'));
          });
      });
      

      【讨论】:

      • 这比需要的 jquery 多得多。只要添加了正确的选择器,无论格式如何,我的都可以使用
      • @Jason:我当然同意用更少的代码可以达到同样的效果,但无论如何,我的答案中显示的方法将允许多组复选框存在于单个页面中。
      【解决方案6】:

      在 HTML 表格中试试这个。

      <table class="rptcontenttext" style="width: 100%; border-style: solid; border-collapse: collapse"  
               border="1px" cellpadding="0" cellspacing="0">  
               <thead>  
                 <tr>  
                   <th style="text-align:left;width:10px;">  
                   <input type="checkbox" value="true" name="chkVerifySelection" id="chkVerifySelection" onchange="return     checkAllVerifySelection();" />  
                   </th>  
                   <td class="rptrowdata" align="left">  
                     Employee ID  
                   </td>  
                 </tr>  
               </thead>  
               <tbody style="overflow-y: auto; overflow-x: hidden; max-height: 400px; width: 100%;">  
                   @for (int i = 0; i < Model.EmployeeInformationList.Count; i++)  
                   {      
                 <tr>  
                   <td style="width:10px">    
                     @{  
                     if (Model.EmployeeInformationList[i].SelectStatus==true)  
                       {  
                       @Html.CheckBoxFor(model => model.EmployeeInformationList[i].SelectStatus, new { @class = "VerifyStatus" ,disabled =                  "disabled",@checked="checked" })   
                       }  
                       else  
                          {  
                         @Html.CheckBoxFor(model => model.EmployeeInformationList[i].SelectStatus, new { @class = "VerifyStatus" })   
                          }  
                       }        
                  </td>             
                   <td class="rptrowdata" align="left" style="width: 70px">  
      
                     @Html.Encode(Model.EmployeeInformationList[i].StrEmpID)   
      
                   </td>  
                    <td class="rptrowdata" align="center" style="width: 50px">  
                     @Html.HiddenFor(m=>m.EmployeeInformationList[i].strEmpOldCardNo)  
                      @Html.Encode(Model.EmployeeInformationList[i].strEmpOldCardNo)  
                   </td>  
                 </tr>  
                   }  
               </tbody>  
             </table>  
      

      脚本:

       function checkAllVerifySelection() {  
           var flag = $('input[name=chkVerifySelection]').is(':checked');  
           if (flag) {  
             $(".VerifyStatus").each(function () {  
               $(this).attr('checked', true);  
             });  
           }  
           else {  
             $(".VerifyStatus").each(function () {  
               $(this).attr('checked', false);  
             });  
           }  
           return true;  
         } 
      

      【讨论】:

        【解决方案7】:

        试试这个:

        @Html.CheckBox("CheckAll", false, new { id = "select_all" })
        $('#select_all').click(function () {
            $('.someClass').prop('checked', this.checked)
        }); 
        

        【讨论】:

          【解决方案8】:

          使用下面的代码

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-04-12
            • 2012-05-02
            • 1970-01-01
            • 2012-12-25
            • 1970-01-01
            相关资源
            最近更新 更多