提问者:小点点

如何在用户单击复选框所在的行时切换复选框?


我有一个有2列的表格,第一列显示文本,另一列有一个复选框。

代码如下所示,复选框由JavaScript生成,例如var checkbox=document.createElement(“input”);

<script type="text/javascript">
      function create_table() {

       var data = ["Sandwidch, "Hamburger", "Bacon"];
       var table = document.getElementById("questionTbl");
       for (var option in data) {
          var table = document.getElementById("menu");
          var row = table.insertRow(-1);
          var cell1 = row.insertCell(0);
          cell1.innerHTML = data[option];

          var cell2 = row.insertCell(1);
          var checkbox = document.createElement("input");
          checkbox.type = "checkbox";
          checkbox.name = "choiceCbx";
          cell2.appendChild(checkbox);

                .....   // The remaining rows
        }
      }
      window.onload = create_table;
</script>

<body>
    <table id="menu">
        <tr>
           <th>Food</th>
           <th>Choice</th>
        </tr>
    </table>
</body>

当用户单击表中的某一行时,如果选中了该行上的复选框,则该复选框应变为未选中,反之亦然。

我使用以下代码来切换复选框,但没有效果,它似乎只检测到“th”行,而没有检测到“tr”行:

$(document).ready(function() {
  $('#menu tr').click(function(event) {
    if (event.target.type !== 'checkbox') {
      $(':checkbox', this).trigger('click');
    }
  });
});

我应该如何修改我的代码以使切换功能工作?


共3个答案

匿名用户

你能做到的。。。

null

const table_foods = document.querySelector('#records tbody')

table_foods.onclick=e=>
  {
  if (e.target.matches('input[type=checkbox]')) return  // to not disturb  natural check action
  let chkBx = e.target.closest('tr').querySelector('input[type=checkbox]')
  chkBx.checked = !chkBx.checked  
  }
 /* cosmetic part */

table {
  border-collapse: collapse;
  margin-top: 25px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  } 
thead {
  background-color: aquamarine;
  }
tbody {
  background-color: #b4c5d8;
}
td, th {
  border: 1px solid grey;
  padding: .3em .7em;
}
<table id="records" class="content">
  <thead>
    <tr> <th>Food</th> <th>Choice</th> </tr>
  </thead>
  <tbody>
    <tr>
      <td>Sandwitch</td>
      <td><input type="checkbox" name="answerCbx-1" /></td>
    </tr>
    <tr>
      <td>pizza</td>
      <td><input type="checkbox" name="answerCbx-2" /></td>
    </tr>
  </tbody>
</table>

匿名用户

试试这个。 此外,您可能希望在您的问题中添加更多细节,因为HTML不包含任何复选框

https://forum.jquery.com/topic/toggle-checkboxs-in-a-table-after-click-function

匿名用户

你能把问题说清楚吗?因为我在那边找不到任何复选框