使用表单输入设置 cookie

Setting cookies with form input

我正在尝试使用用户对网络表单的输入来制作用户名 cookie。但是它不起作用,我不知道为什么。你知道问题出在哪里吗?

<form>
    <input type="text" value="Enter Your Nickname" id="nameBox">
    <input type="button" value="Go!" id="submit" onClick="setCookie();">
<form>


<script>
    var today = new Date();
    var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days

    function setCookie(name, value){
        document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
    }
    //this should set the UserName cookie to the proper value;
    function storeValues(form){
        setCookie("userName", form.submit.value);
        return true;
    }

</script>
</body>

将表格更改为:

<form onsubmit="storeValues(this)">
<input type="text" value="Enter Your Nickname" id="nameBox">
<input type="submit" value="Go!" id="submit">
<form>

并将 storeValues(form) 函数用于:

{
   setCookie("userName", form.nameBox.value);
   return true;
}

您可以查看下面的代码,它可能会对您有所帮助。

<html>
<head>
    <script>
var today = new Date();
  var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days

  function setCookie(name, value)
  {
    document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
  }
function putCookie(form)
                //this should set the UserName cookie to the proper value;
  {
   setCookie("userName", form[0].usrname.value);

    return true;
  }

  </script>
</head>
<body>
<form>
 <input type="text" value="Enter Your Nickname" id="nameBox" name='usrname'>
 <input type="button" value="Go!" id="submit" onclick="putCookie(document.getElementsByTagName('form'));">
</form>
</body>


</html>

虽然定义的函数名称应该是 putCookies 而不是 storeValues 和函数调用,但您可以这样做: putCookie(document.getElementsByTagName('form'));

在函数定义中,cookie 值可以从下面的表单中获取: setCookie("userName", 表格[0].usrname.value);

表单元素应该有属性:name='usrname'

它肯定会为您的用户名和表单元素设置 cookie。