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

如何使用表单外的按钮提交动态生成的表单数据到Google Sheet

问题原因

  • 动态表单生成函数createForm2仅定义未调用,页面加载完成后不会自动渲染表单
  • 外部提交按钮ID为submit,但原有代码绑定的是不存在的#ok元素的点击事件,触发逻辑完全不匹配
  • 直接调用原生form.submit()方法会跳过你提前绑定的submit事件监听器,不会执行对接Google Sheet的fetch提交逻辑
  • 你注释掉了e.preventDefault(),表单提交时会触发默认跳转行为,打断提交流程

额外小提示:你的HTML代码存在笔误,<head>结束标签后多写了一个多余的</body>,建议删除避免页面渲染异常。

修改后的jQuery代码

$(document).ready(function(){ 
  var formData = ["Name","Email","Phone"];
  // 页面加载完成后调用函数生成表单
  createForm2();

  function createForm2(){
    $("#share").append('<form name="google-sheet">');
    for(var f=1; f<4; f++){
      $("#share form").append('<br><label>'+ f +'</label><input type="text" placeholder="'+ formData[f-1] + '" name="' + formData[f-1] + '"/>');
    }
    $("#share form").append('<br><input type="submit" id="savebutton" value="Save" />');

    const scriptURL = 'https://script.google.com/macros/s/AKfycbwOE4ndEngGXcIerdQ708EUI0O1qdjJ7T2YTpGmzJYe_0VL3m4YlPzt9zrMl8oSewqG-Q/exec'
    const form = document.forms['google-sheet']
          
    form.addEventListener('submit', e => {
      // 阻止表单默认跳转行为
      e.preventDefault()
      fetch(scriptURL, { method: 'POST', body: new FormData(form)})
        .then(response => alert("Thanks for Contacting us..! We Will Contact You Soon..."))
        .catch(error => alert("An error occured while processing your request"))
    })
    
    // 绑定外部FORM SUBMIT按钮的点击事件,主动触发自定义submit逻辑
    $("#submit").on("click",function(){
      form.dispatchEvent(new Event('submit'));
    });
  }
});

修改后点击内部Save按钮和外部FORM SUBMIT按钮都可以正常提交数据到Google Sheet。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:24:05