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

如何在表单OnSubmit事件中为多个表单元素设置Cookie?

解决方案

首先要指出,你当前的setCookie函数只计算了过期时间,但没有实际将Cookie写入浏览器,这是第一个需要修复的问题。接下来,我们可以通过一个统一的提交处理函数,批量将指定字段存入Cookie,实现你要的需求。

修改后的完整代码

<html>
<head>
  <script>
    function setCookie(cookieName, cookieValue, nDays) {
      var today = new Date();
      var expire = new Date();

      if (!nDays) nDays = 1;

      expire.setTime(today.getTime() + 3600000 * 24 * nDays);
      // 补充Cookie写入逻辑,对值编码避免特殊字符问题
      document.cookie = `${cookieName}=${encodeURIComponent(cookieValue)}; expires=${expire.toUTCString()}; path=/`;
    }

    function handleFormSubmit(form) {
      // 定义需要存入Cookie的字段名集合
      const targetFields = ['first', 'last', 'social', 'email', 'location'];
      
      // 遍历字段,逐个存入Cookie
      targetFields.forEach(fieldName => {
        const fieldElement = form[fieldName];
        if (fieldElement) {
          setCookie(fieldName, fieldElement.value, 365);
        }
      });

      // 如需表单正常提交则返回true,仅存Cookie不提交则返回false
      return true;
    }
  </script>
</head>
<body>
  <form onsubmit="return handleFormSubmit(this);">
    <input name="first" type="text" required />
    <input name="last" type="text" required />
    <input name="social" type="text" required />
    <input name="email" type="email" required />
    <select name="location">
      <option value="location1">Location 1</option>
      <option value="location2">Location 2</option>
    </select>
    <input type="submit" value="Submit">
  </form>
</body>
</html>

关键改动说明

  • 修复setCookie函数:添加了document.cookie的赋值语句,这是写入Cookie的核心操作;同时用encodeURIComponent对Cookie值编码,避免空格、特殊字符导致的存储异常。
  • 新增handleFormSubmit处理函数:通过字段名列表批量处理Cookie存储,后续要新增或移除字段,只需修改targetFields数组即可,逻辑更清晰易维护。
  • 修改表单onsubmit事件:调用新的处理函数并传入当前表单对象,利用表单的name属性直接获取对应字段元素,比querySelector更简洁可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:35:20