使用表单输入设置cookie

Han*_*ach 6 javascript forms cookies

我正在尝试使用用户对Web表单的输入来创建用户名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>
Run Code Online (Sandbox Code Playgroud)

Ruc*_*ree 6

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

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