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

JQuery实现复选框联动对应文本输入框的显示隐藏及值清空的问题求助

JQuery实现复选框联动对应文本输入框的显示隐藏及值清空的问题求助

看起来你已经把需求和页面结构理得很清楚了,就是在JS选择器和逻辑处理上卡壳了对吧?我来帮你搞定这个问题。

先再确认下你的核心需求:

  • 复选框组name="options[33][]",每个选项对应不同值(260、261等)
  • 对应文本框name="options_qty[33][对应值]",初始隐藏
  • 点击复选框:选中时显示对应文本框;取消选中时隐藏文本框并清空它的值

你之前的代码出错,大概率是因为name属性里的[和]是CSS选择器的特殊字符,直接用常规写法匹配会触发语法错误。下面给你两种靠谱的解决方案:

方案一:用filter方法匹配目标文本框(推荐,直观不易错)

这种方法直接通过元素原生的name属性做精准匹配,避开特殊字符的转义问题:

// 给目标复选框绑定点击事件
$('input[name^="options[33]"]').click(function () { 
    const $checkbox = $(this);
    const checkboxValue = $checkbox.val(); 
    // 构造对应文本框的name值
    const targetInputName = `options_qty[33][${checkboxValue}]`;
    
    // 精准筛选出对应name的文本框
    const $targetInput = $('input').filter(function() {
        return this.name === targetInputName;
    });

    if ($checkbox.is(':checked')) {
        // 复选框选中时,显示文本框
        $targetInput.show();
    } else {
        // 取消选中时,隐藏文本框并清空内容
        $targetInput.hide().val('');
    }
});

方案二:转义特殊字符后直接用选择器

如果你习惯用属性选择器写法,需要把[和]转义成\\[和\\],代码如下:

$('input[name^="options[33]"]').click(function () { 
    const $checkbox = $(this);
    const checkboxValue = $checkbox.val(); 
    // 转义特殊字符后的选择器
    const targetSelector = `input[name="options_qty\\[33\\]\\[${checkboxValue}\\]"]`;
    const $targetInput = $(targetSelector);

    if ($checkbox.is(':checked')) {
        $targetInput.show();
    } else {
        $targetInput.hide().val('');
    }
});

额外优化建议

如果想让代码更易维护,可以给复选框加个data属性直接关联对应文本框的name,比如HTML结构改成这样:

<input type="checkbox" name="options[33][]" value="260" data-target-input="options_qty[33][260]">
<input type="text" name="options_qty[33][260]" style="display: none;">

然后JS代码可以简化成:

$('input[name^="options[33]"]').click(function () { 
    const $checkbox = $(this);
    const targetInputName = $checkbox.data('target-input');
    const $targetInput = $('input').filter(function() {
        return this.name === targetInputName;
    });

    $checkbox.is(':checked') ? $targetInput.show() : $targetInput.hide().val('');
});

这样就不用手动拼接name字符串,减少出错概率。

备注:内容来源于stack exchange,提问作者sdssrr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 10:08:01