简体   繁体   English

选中主复选框时,如何将复选框设置为在数据表列中选中

[英]How can I set checkbox to checked in a datatable column when a master checkbox is checked

I have a datatable for class attendance that is comprised of a student name and 4 columns of checkboxes per row.我有一个 class 出勤数据表,其中包含学生姓名和每行 4 列复选框。 The Select All column is for the user to dynamically set checked/unchecked attribute for the remaining checkboxes in the row. Select All 列供用户动态设置行中剩余复选框的选中/未选中属性。 Ultimately, the form will be saved and the database updated with the value of the checkboxes.最终,表单将被保存并使用复选框的值更新数据库。 When the form is presented, the database does not contain a record of what is presented to the user, it will be inserted when the form is saved.当表单呈现时,数据库不包含呈现给用户的记录,它将在表单保存时插入。

Select All  Student Name    On Time  Present  Contributing  Prep Lesson 
     x      Mickey Mouse        o       o          o            o

HTML: HTML:

<table id="UserTable" class="table table-bordered"> 
    <thead>
      <th style="text-align:center;">Select All</th>
      <th style="text-align:center;">Student Name</th>
      <th style="text-align:center;">On Time</th>
      <th style="text-align:center;">Present</th>
      <th style="text-align:center;">Contributing</th>
      <th style="text-align:center;">Prep. Lesson</th>
    </thead>

    <tbody>
        <?php if(!empty($students)) { ?>
        <?php foreach($students as $student) { ?>
          <tr>
            <div class="container content">
              <!-- select all -->
              <td style="text-align:center;"><input type="checkbox" id="select-all" onchange="selectAll(this)"></td>
              <!-- student -->
              <td class="student-name"><?php echo $student['first_name'] . ' ' . $student['last_name'] ?></td>
              <!-- on-time -->
              <td class="on-time" style="text-align:center;"><input type="checkbox" id="on-time"></td>
              <!-- Present -->
              <td class="present" style="text-align:center;"><input type="checkbox" id="present"></td>
              <!-- contributing -->
              <td class="contribute" style="text-align:center;"><input type="checkbox" id="contribute"></td>
              <!-- prepared lesson -->
              <td class="prep-lesson" style="text-align:center;"><input type="checkbox" id="prep-lesson"></td>            
          </tr>  
      <?php }} ?>
    </tbody>
</table>
Attempts at Javascript code which do not work:
<script type="text/javascript">

      $(document).ready(function(){
        $('#UserTable').DataTable();
      });

      $('#UserTable tbody').on( 'click', 'tr td:eq(0)', function () {
        //var onTime = $(this).parents('#userTable tbody").siblings('#on-time');         
        //$(onTime).attr('checked', true);
        alert("col1");
      });

      function selectAll(elem) {
        alert('in onChange');
        var table = $('#UserTable').DataTable();
        if(elem.checked) {
          // var onTime = $(this).parents('#userTable tbody').siblings('.on-time');     
          // var colData = table.column(this).data();          
          // $(onTime).attr('checked', true);

          alert('checked');
        }
        else {
          alert ('unchecked');
        }
      }
</script>
Thanks for your help,
Dennis

In a group with a “check all” checkbox, the grouping checkbox should also update dependent on the other checkboxes' states.在带有“全选”复选框的组中,分组复选框也应该根据其他复选框的状态进行更新。 So after checking “check all“ and removing one dependent check, it should represent that indeterminate state .因此,在检查“全部检查”并删除一项相关检查后,它应该表示不确定 state

So the suggestion here does the following:因此,这里的建议执行以下操作:

  • Establish groups of checkboxes by iterating on <tr> elements通过迭代<tr>元素来建立复选框组
  • Extract the first checkbox found inside as the grouping checkbox提取里面的第一个复选框作为分组复选框
  • Update dependent checkboxes if the grouping one changes state by binding to the `change' event如果分组通过绑定到“更改”事件更改 state,则更新相关复选框
  • And update the grouping checkbox if one of the dependent boxes change state如果依赖框之一更改 state,则更新分组复选框
    • Filter the list of checkboxes to find those that are checked with Array.filter()过滤复选框列表以查找使用Array.filter()选中的复选框
    • Count the checked checkboxes计算选中的复选框
    • Uncheck grouping box if 0 dependent boxes are checked如果选中了 0 个相关框,则取消选中分组框
    • Check if all dependent boxes are checked检查是否选中了所有相关框
    • Set indeterminate state for any other case为任何其他情况设置不确定的 state

Key to this solution is that by binding event listeners from the NodeList allows easily grouping the checkboxes.该解决方案的关键是通过从 NodeList 绑定事件侦听器可以轻松地对复选框进行分组。 Using onclick="listener" would render that difficult.使用onclick="listener"会变得很困难。

Also it's using the change event , as you should always use events that are data-oriented and not interaction-oriented.它还使用了change事件,因为您应该始终使用面向数据而不是面向交互的事件。 Users could use the keyboard or other means to change a checkboxe's state.用户可以使用键盘或其他方式更改复选框的 state。

 document.querySelectorAll('tbody tr').forEach(tr => { // all the variables inside here are valid for one tr, establishing a checkbox group const [checkAll, ...checkboxes] = tr.querySelectorAll('input[type="checkbox"]'); // propagate checked state down to dependent checkboxes // we simply copy the grouping boxes' state to the dependent boxes checkAll.addEventListener('change', e => checkboxes.forEach(c => c.checked = e.currentTarget.checked)); // propagate checked state up depending on group state checkboxes.forEach(c => c.addEventListener('change', e => { // list all checked dependent checkboxes const checked = checkboxes.filter(cb => cb.checked); // and compare count with the whole group if (checked.length === checkboxes.length) { // all are checked checkAll.checked = true; checkAll.indeterminate = false; } else if (checked.length === 0) { // none is checked checkAll.checked = false; checkAll.indeterminate = false; } else { // some are checked checkAll.indeterminate = true; } })); });
 <table> <thead> <tr> <th style="text-align:center;">Select All</th> <th style="text-align:center;">Student Name</th> <th style="text-align:center;">On Time</th> <th style="text-align:center;">Present</th> <th style="text-align:center;">Contributing</th> <th style="text-align:center;">Prep. Lesson</th> </tr> </thead> <tbody> <tr> <div class="container content"> <:-- select all --> <td style="text-align;center:"><input type="checkbox" aria-label="Check all criteria for Mickey Mouse"></td> <;-- student --> <td class="student-name"> Mickey Mouse </td> <:-- on-time --> <td class="on-time" style="text-align;center:"><input type="checkbox" id="on-time"></td> <;-- Present --> <td class="present" style="text-align:center;"><input type="checkbox" id="present"></td> <:-- contributing --> <td class="contribute" style="text-align;center:"><input type="checkbox" id="contribute"></td> <;-- prepared lesson --> <td class="prep-lesson" style="text-align:center;"><input type="checkbox" id="prep-lesson"></td> </tr> <tr> <div class="container content"> <:-- select all --> <td style="text-align;center:"><input type="checkbox" aria-label="Check all criteria for Mini Mouse"></td> <;-- student --> <td class="student-name"> Mini Mouse </td> <!-- on-time --> <td class="on-time" style="text-align:center;"><input type="checkbox" id="on-time"></td> <!-- Present --> <td class="present" style="text-align:center;"><input type="checkbox" id="present"></td> <!-- contributing --> <td class="contribute" style="text-align:center;"><input type="checkbox" id="contribute"></td> <!-- prepared lesson --> <td class="prep-lesson" style="text-align:center;"><input type="checkbox" id="prep-lesson"></td> </tr> </tbody> </table>

Other Improvements其他改进

The code included an id="select-all" inside a for loop.该代码在 for 循环中包含一个id="select-all" This is invalid, as IDs need to be unique.这是无效的,因为 ID 必须是唯一的。 I removed it, because the suggested solution doesn't need any IDs.我删除了它,因为建议的解决方案不需要任何 ID。

I also added a specific label for the first checkbox, to be sure.可以肯定的是,我还为第一个复选框添加了特定的 label。 Assistive technology is often able to determine the labels for inputs inside a table from the table structure.辅助技术通常能够从表结构中确定表内输入的标签。

    <td style="text-align:center;"><input type="checkbox" aria-label="Check all criteria for Mickey Mouse"></td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM