如何点击数据表格内按钮时取消对应行复选框的选中状态
解决点击按钮更新Qty并取消对应行复选框选中状态的问题
我有如下HTML表格代码,通过PHP循环渲染数据:
<table id='data-table'> <thead> <tr> <th>No</th> <th>Name Items</th> <th>Qty</th> <th>Price</th> <th>Action</th> <th>Check</th> </tr> </thead> <tbody> <?php foreach($data as $d) : ?> <tr> <td><?= $no++ ?></td> <td><?= $d['name'] ?></td> <td><?= $d['qty'] ?></td> <td><?= $d['price'] ?></td> <td><button type='button' class='btn' name='up'>up</button></td> <td><input type='checkbox'></td> </tr> <?php endforeach ?> </tbody> </table>
需求是点击每行的up按钮时,更新该行的Qty数值(加1),同时如果该行的复选框处于选中状态,就取消选中。我已经写了部分jQuery代码,但不知道如何实现取消复选框选中的功能:
$('#data-table tbody').on('click', '.btn[name="up"]', function() { const row = $(this).closest('tr')[0]; const qty = Number(row.cells[2].innerHTML); const tqty = qty + 1; row.cells[2].innerHTML = tqty; });
修改后的代码实现
只需要在现有代码中添加一行,找到当前行的复选框并设置其选中状态为未选中即可:
$('#data-table tbody').on('click', '.btn[name="up"]', function() { const row = $(this).closest('tr')[0]; const qty = Number(row.cells[2].innerHTML); const tqty = qty + 1; row.cells[2].innerHTML = tqty; // 取消当前行复选框的选中状态 $(this).closest('tr').find('input[type="checkbox"]').prop('checked', false); });
代码说明
$(this).closest('tr'):定位当前点击按钮所在的父级<tr>元素.find('input[type="checkbox"]'):在该行内筛选出复选框元素.prop('checked', false):通过jQuery的prop()方法将复选框的选中状态设为未选中
内容的提问来源于stack exchange,提问作者Riansyah Jalil
相关产品推荐
相关产品推荐

