首页 > 解决方案 > 将逗号列表中的多个复选框选择发布到 Google 表格

问题描述

我正在使用脚本将 HTML 表单中的数据输入到 Google 表格中。有没有办法可以修改它(或添加其他内容),以便我的复选框字段将作为列表输入到我的 Google 表格中,用逗号分隔?

因此,使用下面的表格,如果选中所有框,我希望 Google 表格中的“时间”单元格列出上午 9 点、上午 10 点、上午 11 点。现在,它只显示选中的第一个框的值。

表格示例:

<form>
<input type="checkbox" name="time" value="9am">
<label for="time">9:00am</label><br>
<input type="checkbox" name="time" value="10am">
<label for="time">10:00am</label><br>
<input type="checkbox" name="time" value="11am">
<label for="time">11:00am</label><br>
<button type="submit">Submit times</button>
</form>

脚本(来自https://github.com/jamiewilson/form-to-google-sheets):

<script>
  const scriptURL = 'https://script.google.com/macros/s/XXXX/exec'
  const form = document.forms['submit-to-google-sheet']

  form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, { method: 'POST', body: new FormData(form)})
      .then(response => console.log('Success!', response))
      .catch(error => console.error('Error!', error.message))
  })
</script>

标签: javascripthtmlformsgoogle-apps-scriptcheckbox

解决方案


如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。

修改点:

  • 在您的 HTML 中,复选框使用相同的名称。是time。在这种情况下,您可以e.parameters["time"]在 Google 端检索这些值。

修改后的脚本:

请按如下方式修改您的 Google Apps 脚本。

从:
return header === 'timestamp' ? new Date() : e.parameter[header]
至:
return header === 'timestamp' ? new Date() : (header == "time" ? e.parameters[header].join(",") : e.parameter[header]);
  • 在这种情况下,如果time标题行中不存在,则不放置这些值。请注意这一点。

笔记:

  • 当您修改 Web Apps 的脚本时,请将 Web Apps 重新部署为新版本。这样,最新的脚本就会反映到 Web 应用程序中。请注意这一点。

参考:

很遗憾,我看不到您当前的 Google Apps 脚本和电子表格。因此,如果上述修改没有解决您的问题,我深表歉意。当时,为了正确理解您的情况,您能否提供包含整个脚本的示例电子表格?通过这个,我想检查一下。


推荐阅读