使用原始javascript创建cookie

时间:2015-03-04 20:52:12

标签: javascript cookies

应为以下字段创建Cookie:fname,lname,street,city,state,zip,email和phone1-3。应创建持久性cookie,有效期为1年。当用户返回页面时,应该读取cookie并将单个表单字段值恢复为保存的cookie值。

<html>
<body>
<input name="fname" id="fname">
<input name="lname" id="lname">
<input id="street" name="street" type="text">
<input id="city" name="city" type="text">
<select id="state" name="state"><option value="" selected="selected">Choose</option>
<input id="zip" name="zip" type="text">
<input name="email" id="email">
( <input id="phone1" name="phone1" size="3"> )
  <input id="phone2" name="phone2" size="3"> - 
  <input id="phone3" name="phone3" size="4">

<script type="text/javascript>

var regForm = document.getElementById("registration");
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var street = document.getElementById("street").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").options;
var zip = document.getElementById("zip").value;
var email = document.getElementById("email").value;
var phone1 = document.getElementById("phone1").value;
var phone2 = document.getElementById("phone2").value;
var phone3 = document.getElementById("phone3").value;

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;
    alert("Cookie being created " + document.cookie);
}
createCookie("first", fname, 365);

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可能希望在函数中使用私有变量,例如cookieToCreate。

function createCookie(name, value, days) {
  var cookieToCreate = '';  // Private var
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
  }
  else var expires = "";
  cookieToCreate = name + '=' + value + expires + '; path=/;';
  document.cookie = cookieToCreate;
  alert("Cookie being created " + cookieToCreate);
}