单击同一行中的任何复选框时,选中/取消选中表格行中的复选框 [英] Check/uncheck a checkbox in the table row when any checkbox in the same row is clicked

查看:102
本文介绍了单击同一行中的任何复选框时,选中/取消选中表格行中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表格如下,每行的第一列和最后一列都有复选框。

I have a simple table as following which has checkboxes in the first and last columns of each row.

<table style="width:100%">
  <tr>
    <td><input type="checkbox" /></td>
    <td>Smith</td> 
    <td><input type="checkbox" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Jackson</td> 
    <td><input type="checkbox" /></td>
  </tr>
</table>

问题:
当我选中/取消选中第一行中最后一列的复选框时,应检查/取消选中同一行中的第一列复选框。同样,如果我选中/取消选中第一列的复选框,则应选中/取消选中相应的最后一列复选框。

Problem: When I check/uncheck the last column's checkbox in the first row, the first column's checkbox in the same row should be checked/unchecked. Similarly, if I check/uncheck the first column's checkbox, the corresponding last column checkbox should be checked/unchecked.

如何在javascript中实现此目的?任何帮助或指示都会非常感激。

How can I achieve this in javascript? Any help or pointers would be really appreciated.

这是我创建的小提琴:小提琴

Here is the fiddle which I have created: Fiddle

谢谢。

推荐答案


使用:复选框选择器选择输入类型复选框元素。

Use :checkbox selector to select input type checkbox elements.

试试这个:

$(':checkbox').on('change', function() {
  $(this).closest('tr').find(':checkbox').prop('checked', this.checked);
});

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>

使用JavaScript:


使用 querySelectorAll('[type =checkbox]')查找复选框元素。

试试这个:

var checkboxes = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(checkboxes, function(checkbox) {
  checkbox.onchange = function() {
    var currentRow = this.parentNode.parentNode;
    var cbElems = currentRow.querySelectorAll('[type="checkbox"]');
    [].forEach.call(cbElems, function(cb) {
      cb.checked = this.checked;
    }.bind(this))
  };
});

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}

<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>

这篇关于单击同一行中的任何复选框时,选中/取消选中表格行中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆