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

如何使用jQuery将多个表单内容合并到最终提交表单中?

如何将分区域表单合并到最终提交表单?

我正在创建一个包含多个分区域的表单,希望将每个区域表单的内容添加到名为finalForm的最终提交表单中,请问该怎么实现?

现有HTML代码

<form id='1'  name='1' method='POST' action='#'>
    <input type='text' id='blah' name='blah'>
    <input type='text' id='blahblah' name='blahblah'>
    <input type='button' id='sub1' value='Submit'>
</form>
<form id='2' class='section' name='2' method='POST' action='#'>
    <input type='text' id='blah2' name='blah2'>
    <input type='text' id='blahblah2' name='blahblah2'>
    <input type='button' id='sub2' value='Submit'>
</form>

<form id='finalForm' name='finalForm' method='POST' action='#'>
</form>

初始jQuery代码(待完善)

$('#sub1, #sub2').click(function(){
     // 把当前点击表单的所有数据添加到$('#finalForm')中
 });

实现方案

直接用下面的jQuery代码就能实现需求:

$('#sub1, #sub2').click(function(){
    // 找到当前按钮所属的表单
    const targetForm = $(this).closest('form');
    // 遍历表单里的文本输入框,克隆后添加到finalForm
    targetForm.find('input[type="text"]').each(function(){
        // 克隆输入框,保留用户输入的内容和所有属性
        const inputClone = $(this).clone();
        $('#finalForm').append(inputClone);
    });
});

进阶优化:避免重复添加

如果不想让同一个分表单的内容被多次添加,可以给已处理的表单加个标记类,防止重复操作:

$('#sub1, #sub2').click(function(){
    const targetForm = $(this).closest('form');
    // 检查表单是否已经处理过
    if(targetForm.hasClass('added')) return;
    // 标记为已处理
    targetForm.addClass('added');
    
    targetForm.find('input[type="text"]').each(function(){
        const inputClone = $(this).clone();
        $('#finalForm').append(inputClone);
    });
});

注意事项

  • 原代码里第一个表单的method写了POTS,属于笔误,改成POST才符合表单规范。
  • 确保所有输入框的name属性符合后端接收要求,如果有重名需要调整,避免提交时数据冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:09:22