【问题标题】:Check All the checkboxes in a table when a particular checkbox is clicked?单击特定复选框时检查表中的所有复选框?
【发布时间】:2015-12-20 16:03:37
【问题描述】:

我通过这种方式使用 tr 和 td 将复选框动态添加到表中。

var arr=[1,2,3];

                var trtest = "<tr>";
                trtest = trtest +"<tr><td><input type='checkbox' onclick=onAllCheckBoxClick('" + arr+ "') class = 'all' id ='all'>All</td></tr>";

$.each(arr, function(i, tmp) {
                    trtest = trtest +"<tr><td><input type='checkbox' onclick=onCheckBoxClick('" + this+ "','" + arr+ "') class = 'all' id ='"+tmp+"'/>"+tmp+"</td></tr>";
                });

这段代码正在运行,而且我通过这种方式获得了 4 个复选框,

All
    1

    2

    3

在这里,当我尝试选中所有复选框时,必须选中同一张表 1、2、3 中的所有其他复选框。

我尝试将此点击事件添加到所有复选框。

function onAllCheckBoxClick(arr){
        var checked = $('#all').attr('checked');
        if(checked =="checked") {
            $.each(arr.split(","), function(i, tmp) {
                    $('#'+tmp).attr('checked',true);
            }); 
        }

}

问题是当我选中 All 时,它只检查同一张表中的 3(即最后一个复选框),其中 1,2 仍未选中。

但我希望在选中所有复选框时选中所有 1、2、3 个复选框。

谁能帮我解决这个问题?

【问题讨论】:

  • $('input:checkbox').prop('checked',true)

标签: javascript jquery html checkbox html-table


【解决方案1】:

$(document).ready(function(){
 
 $('#mainChkBox').change(function(){
     $(':checkbox').prop('checked', this.checked);
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <th><input type='checkbox' id = 'mainChkBox'/>Click here<th>
  </thead>
  <tbody>
   <tr>  <td><input type='checkbox'/><td></tr>
    
   <tr>  <td><input type='checkbox'/><td></tr>
    
   <tr>  <td><input type='checkbox'/><td></tr>
    
   <tr>  <td><input type='checkbox'/><td></tr>
    
   <tr>  <td><input type='checkbox'/><td></tr>
    
   <tr>  <td><input type='checkbox'/><td></tr>
    
   <tr>  <td><input type='checkbox'/><td></tr>
    
  </tbody>
  <table>

【讨论】:

    【解决方案2】:

    试试这个:

    $(function(){
        $("#master").on("click",function(event){
            $(":checkbox").attr('checked', true);
        });
    });
    <a href="#" id="master">Check All</a>
    <input type="checkbox"/>
    <input type="checkbox"/>
    <input type="checkbox"/>
    <input type="checkbox"/>
    <input type="checkbox"/>

    【讨论】:

    【解决方案3】:

    其他方法

    $('#all').toggle(
        function() { 
            $(':checkbox').attr('checked','checked'); 
        },
        function() { 
            $(':checkbox').removeAttr('checked'); 
        }
    );
    

    https://jsfiddle.net/n3huxo8s/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-04
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2013-05-08
      相关资源
      最近更新 更多