使用表单输入设置cookie

时间:2015-05-24 03:56:53

标签: javascript forms cookies

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

<form>
    <input type="text" value="Enter Your Nickname" id="nameBox">
    <input type="button" value="Go!" id="submit" onClick="putCookie">
<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>

2 个答案:

答案 0 :(得分:5)

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

<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(&#39;形式&#39;));

在函数定义中,cookie值可以从表单中获取,如下所示: setCookie(&#34; userName&#34;,form [0] .usrname.value);

表单元素应具有以下属性:name =&#39; usrname&#39;

肯定会使用表单元素为您的用户名设置Cookie。

答案 1 :(得分:0)

将表单更改为:

model.find

并且storeValues(form)函数为:

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