使用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
2to250inclusive usinglet i = 2; i <= 250; i++. - Form Existence Check: The
if (!form) continueline 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
letin the loop ensures each iteration gets its ownformreference, so the event listener uses the correct form when triggered.
This approach is efficient, maintainable, and avoids repetitive code.
内容的提问来源于stack exchange,提问作者wmr123
相关产品推荐
相关产品推荐

