You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现复选框未勾选时禁用所有输入框?附现有代码

没问题,这个需求很容易实现,咱们用JavaScript(原生或者jQuery都可以)就能搞定核心逻辑:让每一行的复选框单独控制该行对应的输入框——当复选框未勾选时禁用输入框,勾选时恢复可用。

先给你的HTML结构补全并优化一下(给元素加类方便定位):

<tr class="select_tr">
    <td><?= ucwords($food_name); ?></td>
    <td class="form-group text-center">
        <input value="<?= $order_food_id; ?>" type="checkbox" name="select_food[]" class="food-select" checked>
    </td>
    <td class="form-group">
        <input value="<?= $order_food_total_members; ?>" type="text" name="total_members[]" class="form-control member-input" placeholder="Total Members">
    </td>
</tr>

方案一:原生JavaScript(无依赖)

这种方案不需要额外库,兼容性好:

// 先处理页面加载时的初始状态
const checkboxes = document.querySelectorAll('.food-select');
checkboxes.forEach(checkbox => {
    const row = checkbox.closest('.select_tr');
    const input = row.querySelector('.member-input');
    // 根据复选框初始状态设置输入框是否禁用
    input.disabled = !checkbox.checked;
});

// 给复选框绑定change事件
checkboxes.forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        // 找到当前行的输入框
        const input = this.closest('.select_tr').querySelector('.member-input');
        // 切换禁用状态
        input.disabled = !this.checked;
    });
});

方案二:jQuery(如果你项目已经引入了jQuery)

代码会更简洁:

// 初始化状态
$('.food-select').each(function() {
    $(this).closest('.select_tr').find('.member-input').prop('disabled', !$(this).is(':checked'));
});

// 绑定切换事件
$('.food-select').on('change', function() {
    $(this).closest('.select_tr').find('.member-input').prop('disabled', !$(this).is(':checked'));
});

额外提示:处理动态添加的行

如果你的表格行是通过AJAX或者其他方式动态生成的,需要用事件委托来确保新添加的复选框也能生效:

原生JS事件委托:

document.addEventListener('change', function(e) {
    if (e.target.classList.contains('food-select')) {
        const row = e.target.closest('.select_tr');
        const input = row.querySelector('.member-input');
        input.disabled = !e.target.checked;
    }
});

jQuery事件委托:

$(document).on('change', '.food-select', function() {
    $(this).closest('.select_tr').find('.member-input').prop('disabled', !$(this).is(':checked'));
});

核心思路就是通过closest('.select_tr')定位到当前复选框所在的行,再精准找到该行内的输入框,避免影响其他行的元素,确保每一行的控制都是独立的。

内容的提问来源于stack exchange,提问作者Mohan Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:16:26