如何正确获取Checkbox的值?解决表单提交至Google Sheets时复选框值返回'on'的异常问题
Hey there, let's figure out why your checkboxes are returning 'on' instead of your set values, and fix the issue so you can submit multiple selected materials to Google Sheets correctly.
1. First, Fix the HTML Syntax Error
Looking at your HTML, the second checkbox has a typo in its closing tag:
<input name="Materials" type="checkbox" value="Vinyl"//>
That extra / before > is causing the browser to misparse the value attribute, so it falls back to the default checkbox value 'on'. Change it to:
<input name="Materials" type="checkbox" value="Vinyl"/>
2. Fix the JavaScript Logic for Checkboxes
Your current code has two key issues with checkboxes:
- It adds all checkboxes to the form data, regardless of whether they're checked
- Multiple checkboxes with the same name get overwritten in the
objobject, so only the last one's value gets submitted
Here's the corrected JavaScript code that handles checkboxes properly:
var formData = new FormData(); document.querySelectorAll("form").forEach(f => { f.querySelectorAll("input").forEach(ele => { // Handle checkboxes: only add if checked if (ele.type === 'checkbox') { if (ele.checked) { formData.append(ele.name, ele.value); } } else { // Handle other input types like text, etc. formData.append(ele.name, ele.value || ""); } }); }) const scriptURL = 'https://script.google.com/macros/s//exec' fetch(scriptURL, { method: 'POST', body: formData}) .then(response => alert("You have successfully submitted.")) .catch(error => console.error('Error!', error.message))
What Changed?
- We removed the intermediate
objobject because it can't handle multiple values for the same key (it overwrites them) - For checkboxes, we first check if they're
checkedbefore adding their value toformData - Using
formData.append()directly for each input means multiple selected checkboxes with the same name will all be sent to Google Sheets (as separate entries under the same key)
3. Handling the Data in Google Apps Script
To receive all selected materials in your Google Apps Script, make sure you use the plural parameters instead of parameter (since it returns an array of values):
function doPost(e) { const materials = e.parameters.Materials; // This will be an array of selected values // Rest of your code to write to Sheets... }
That should fix both the 'on' value issue and allow you to submit multiple selected materials correctly!
内容的提问来源于stack exchange,提问作者NoNam4

