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

模态框中动态添加的Input字段无法随表单提交问题

问题解决:动态添加的表单字段未被提交

核心问题

动态字段未被提交的主要原因是JavaScript模板字符串中误用了HTML实体("、<、>),这些实体在JS中不会被解析为HTML的标签和属性引号,导致生成的input元素属性格式错误,浏览器无法识别为有效表单字段,因此提交时不会包含这些数据。

另外,手动指定数组索引(如componentName[${index}])虽能被PHP处理,但删除行后易出现索引不连续的情况,统一使用无索引的[]更可靠。

修正后的代码

JavaScript代码

function addInput(aplid) {
    var html = `
        <div class="row">
            <div class="col-md-8 mb-3">
                <label for="componentName${$('.repeater-' + aplid + ' .row').length}" class="form-label">Component Name:</label>
                <input type="text" class="form-control" placeholder="Enter component" name="componentName[]" required>
            </div>
            <div class="col-md mb-3">
                <label for="componentScore${$('.repeater-' + aplid + ' .row').length}" class="form-label">Score:</label>
                <input type="text" class="form-control" placeholder="" name="componentScore[]" required>
            </div>
            <div class="col-md mb-3 d-flex align-items-end">
                <button onclick="removeInput(this)" class="btn btn-danger" type="button">
                    <i data-feather="minus-circle" class="feather-sm fill-white"></i> Remove
                </button>
            </div>
        </div>
    `;
     $('.repeater-' + aplid).append(html);
    // 重新渲染feather图标(若使用了该图标库)
    feather.replace();
}

function removeInput(button) {
    $(button).closest('.row').remove();
}

额外检查:提交按钮位置

确保表单提交按钮在<form>标签内部,或通过JS正确触发表单提交。若提交按钮在模态框modal-footer(不在form内),可手动调用submit方法:

<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary" onclick="document.querySelector('form[action=\'print_post.php\']').submit()">Save changes</button>
</div>

修正后效果

提交表单后,print_r($_POST)会输出所有动态添加的字段:

Array ( 
    [id] => 167 
    [componentName] => Array ( 
        [0] => sample1 
        [1] => sample2 
        [2] => sample3 
    ) 
    [componentScore] => Array ( 
        [0] => 10 
        [1] => 20 
        [2] => 30 
    ) 
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:44:52