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

如何将表单用户输入传入提交函数创建Cookie,并实现提交时页面跳转?

Hey there! Let's break down your two questions and fix up your code step by step.

解决需求一:用用户输入作为Cookie名称

To make this work, we need to grab the user's input first, then pass it to the createCookie function as the cookie name. Here's what to adjust:

  1. Add an id to the input field so we can easily fetch its value in JavaScript
  2. Replace the form's direct onsubmit call with a custom handler function (since we need to get the input value first)
  3. In the handler, block the form's default submit behavior (to avoid unwanted page refreshes), then create the cookie with the user's input as the name

Modified code example:

<div class="container-fluid">
  <div class="row">
    <div class="d-flex mx-auto mt-5 mb-5">
      Hello and welcome to the quiz.
    </div>
  </div>
  <div class="row">
    <div class="d-flex mx-auto mb-5">
      <form onsubmit="handleCookieNameSubmit(event)">
        Enter cookie name:
        <input type="text" id="cookieNameInput">
        <input type="submit">
      </form>
    </div>
  </div>
  <div class="row">
    <div class="col-12 col-sm-6 mx-auto">
      <button type="button" id="nextQuestion" class="btn btn-primary d-flex mx-auto mt-2">Lets go!</button>
    </div>
  </div>
</div>

<script>
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

// Handler for requirement 1
function handleCookieNameSubmit(event) {
  // Stop the form from reloading the page
  event.preventDefault();
  // Get the user's input for the cookie name
  const cookieName = document.getElementById('cookieNameInput').value.trim();
  
  // Validate input to avoid empty cookie names
  if (!cookieName) {
    alert("Please enter a cookie name!");
    return;
  }
  
  // Create the cookie (I used a default value here, feel free to adjust it)
  createCookie(cookieName, "default_cookie_value", 7);
}
</script>

解决需求二:用用户输入作为Cookie值 + 提交后跳转页面

For this scenario, we'll use the user's input as the cookie value, then redirect to another page after setting the cookie. The core adjustments are similar to the first case:

  1. Add an id to the input field
  2. Use a custom submit handler to block default behavior, set the cookie, then trigger the redirect

Modified code example:

<div class="container-fluid">
  <div class="row">
    <div class="d-flex mx-auto mt-5 mb-5">
      Hello and welcome to the quiz.
    </div>
  </div>
  <div class="row">
    <div class="d-flex mx-auto mb-5">
      <form onsubmit="handleCookieValueSubmit(event)">
        Enter name:
        <input type="text" id="usernameInput">
        <input type="submit">
      </form>
    </div>
  </div>
  <div class="row">
    <div class="col-12 col-sm-6 mx-auto">
      <button type="button" id="nextQuestion" class="btn btn-primary d-flex mx-auto mt-2">Lets go!</button>
    </div>
  </div>
</div>

<script>
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

// Handler for requirement 2
function handleCookieValueSubmit(event) {
  // Block default form submission to keep control of the flow
  event.preventDefault();
  // Get the user's input to use as the cookie value
  const username = document.getElementById('usernameInput').value.trim();
  
  // Validate input
  if (!username) {
    alert("Please enter your name!");
    return;
  }
  
  // Create the cookie with fixed name and user-provided value
  createCookie('first_cookie', username, 7);
  // Redirect to your target page (replace with your actual URL)
  window.location.href = "next-quiz-page.html";
}
</script>

Quick Key Notes:

  • event.preventDefault() is crucial here: it stops the form from reloading the page immediately, which would interrupt our cookie setup and redirect.
  • Always validate user input to avoid creating empty cookies (which can cause unexpected behavior).
  • For the redirect, use a relative path for pages on the same domain, or a full URL for external sites.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:17:02