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

如何通过索引选择命名字段?实现type切换时禁用对应pn输入框

问题:带索引字段的jQuery选择器实现表单联动控制

示例HTML代码

<tr class="items">
    <td>
        <select name="type[0]">
            <option value="1">Goods</option><option value="2">Work</option>
        </select>
    </td>
    <td><input type="text" name="pn[0]"></td>
    <td><input type="number" name="qty[0]"></td>
    <td><input type="number" name="price[0]"></td>
</tr>
<tr class="items">
    <td>
        <select name="type[1]">
            <option value="1">Goods</option><option value="2">Work</option>
        </select>
    </td>
    <td><input type="text" name="pn[1]"></td>
    <td><input type="number" name="qty[1]"></td>
    <td><input type="number" name="price[1]"></td>
</tr>

需求

当name为type[索引]的下拉框切换至值2时,清空并禁用对应索引的pn[索引]输入框;切换回其他值时恢复输入框的启用状态,需要实现通用的索引匹配逻辑适配所有带索引的表单元素。

尝试的代码(待完善)

$('select[name="type[*index*]"]').change(function(){
    if($(this).value == 2){
        $('input[name="pn[*index*]"]').prop('disabled', 'disabled');
    } else {
        $('input[name="pn[*index*]"]').prop('disabled', false);
    }
})

解决方案

1. 提取索引值的方法

可以通过正则表达式或字符串分割从下拉框的name属性中提取索引:

  • 正则表达式方式:
const index = $(this).attr('name').match(/type\[(\d+)\]/)[1];
  • 字符串分割方式:
const index = $(this).attr('name').split('[')[1].split(']')[0];

2. 修正后的完整代码

同时需要修正原代码的两个问题:jQuery中获取表单值要用$(this).val(),prop('disabled')的参数应为布尔值而非字符串;另外需添加清空输入框的逻辑:

$('select[name^="type["]').change(function() {
    // 提取当前下拉框的索引
    const index = $(this).attr('name').match(/type\[(\d+)\]/)[1];
    // 定位对应索引的pn输入框
    const targetInput = $(`input[name="pn[${index}]"]`);

    if ($(this).val() === '2') {
        targetInput.val('').prop('disabled', true);
    } else {
        targetInput.prop('disabled', false);
    }
});

3. 更高效的DOM定位方式

如果HTML结构固定(下拉框和对应输入框在同一个.items行内),可以直接通过DOM关系定位,无需提取索引,性能更优:

$('select[name^="type["]').change(function() {
    const targetInput = $(this).closest('.items').find('input[name^="pn["]');

    if ($(this).val() === '2') {
        targetInput.val('').prop('disabled', true);
    } else {
        targetInput.prop('disabled', false);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:05:17