如何通过复选框获取表格对应行的数量输入框?
解决方法
1. 修复HTML重复ID问题
循环生成的元素不能使用相同的id(违反HTML规范),先把复选框和数量输入框的重复id替换为类名:
<form action="{% url 'create-order' %}" method="POST"> {% csrf_token %} <table class="table table-responsive table-borderless"> <thead> <th> </th> <th>Quantity</th> </thead> <tbody> {% for item in items %} <tr class="align-middle alert border-bottom"> <td> <!-- 移除重复id,添加类名item-checkbox --> <input type="checkbox" name="item" value="{{ item.id }}" class="item-checkbox"> </td> <td> <!-- 移除重复id,添加类名quantity-input --> <input class="input quantity-input" name="quantity" min="0" value=0 type="number" disabled> </td> </tr> {% endfor %} </tbody> </table> <div class="submitButton"> <button type="submit" class="lgbtn green">Go to order</button> </div> </form>
2. 修改JavaScript逻辑
去掉原有的onclick绑定(避免重复添加事件监听),改用批量绑定事件的方式,核心通过DOM遍历定位当前行的数量输入框:
// 页面加载完成后绑定事件 document.addEventListener('DOMContentLoaded', function() { // 给所有复选框绑定change事件 document.querySelectorAll('.item-checkbox').forEach(checkbox => { checkbox.addEventListener('change', function() { // 找到当前复选框所在的表格行 const row = this.closest('tr'); // 在当前行内找到对应的数量输入框 const quantity = row.querySelector('.quantity-input'); if (this.checked) { quantity.disabled = false; quantity.value = 1; } else { quantity.disabled = true; quantity.value = 0; } }); }); });
关键说明
closest('tr'):从当前复选框元素向上查找最近的<tr>父元素,确保只操作当前行的元素。querySelector('.quantity-input'):在目标行内精准定位对应数量输入框,避免全局查找导致的错误匹配。- 移除
onclick属性:避免每次点击复选框都重复添加事件监听,防止逻辑多次触发。
内容的提问来源于stack exchange,提问作者Sergey
相关产品推荐
相关产品推荐

