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

使用JavaScript For循环批量绑定form2至form250的Google Sheet提交事件

Batch Bind Submit Events to Forms 2–250

Great question—instead of repeating the code 249 times, a simple for loop will handle this cleanly. Here's how to do it, plus a fix for a small issue in your original code:

// Assuming scriptURL is already defined globally or in scope
for (let i = 2; i <= 250; i++) {
  const formName = `submit-to-google-sheet${i}`;
  const form = document.forms[formName];
  
  // Only proceed if the form exists to avoid errors
  if (!form) continue;
  
  form.addEventListener('submit', e => {
    e.preventDefault();
    fetch(scriptURL, { method: 'POST', body: new FormData(form) })
      .then(response => {
        console.log('Success!', response);
        alert('Successfully Submitted!'); // Fixed: moved inside the success callback
      })
      .catch(error => console.error('Error!', error.message));
  });
}

Key Notes:

  • Loop Range: The loop runs from 2 to 250 inclusive using let i = 2; i <= 250; i++.
  • Form Existence Check: The if (!form) continue line skips any missing forms, so you won't get errors if some form numbers aren't present on the page.
  • Fixed Alert Placement: In your original code, the alert() was passed as the second argument to .then(), which means it ran immediately (not after the fetch succeeded). Moving it inside the first callback ensures it only triggers when the submission is successful.
  • Scoped Form Variable: Using let in the loop ensures each iteration gets its own form reference, so the event listener uses the correct form when triggered.

This approach is efficient, maintainable, and avoids repetitive code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:01:56