简体   繁体   中英

Set cookie and display the value of cookie

I am working on storing and reading information in Cookies. So basically I have two HTML pages with field of name. On page 1 I have to read the field and save the value into a cookie. And then submit, it will go to page 2, read the cookie and display the name that i typed on page 1. However, I could not display the value from page 1 on page 2. Here is my code:

Page 1:

<html>
<head>
<title>Save Value</title>
    <script type="text/javascript">
        function setCookie(cname, cvalue) {
            document.cookie = cname + "=" + cvalue + "; ";
        }
    </script>
</head>
<body>
<form action="display.html" method="get">
<label> 
First Name:
<input name="name" size="20" maxlength="25" type="text" id="name" />
</label>
<input type="submit" value="submit" onclick="setCookie()" />
</form>
</body>
</html> 

Page 2:

    <html>
    <head>
    <title>Display</title>
    <script type="text/javascript">
    function readCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}
</script>
    </head>

    <body>
    <form action="#">
    <label>
    First Name:
    <input name="namefield" size="20" maxlength="25" type="text" id="name" readonly="readonly" />
    </label>
    <script type="text/javascript">
    var val1 = document.getElementById("name").value;
    val1 = readCookie('namefield');
    </script>
    </form>
    </body>
    </html>

Any idea about this problem? Thank you so much!

You call setCookie() without parameters

<input type="submit" value="submit" onclick="setCookie('name', document.getElementById('name').value)" />

Then also your code for reading cookie and seting value is buggy, try to check that jsfiddle, doing all on one page http://jsfiddle.net/ApfJz/44/

Getting cookie and setting value in following way

       <input type="submit" value="Get cookie" onclick="document.getElementById('name2').value = readCookie('name')" />

your code doesn't set value at all and reading wrong cookie name

var val1 = document.getElementById("name").value;
val1 = readCookie('namefield');

so on your Page 2 it could work like that

document.getElementById('name').value = readCookie("name");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM