Cookies are not Storing when i print those cookie values in javascript?

381 views Asked by At

This is my demo.jsp page in that i'm entering data in a textbox and storing in cookies and later printing those stored cookies but initially cookies are storing in browser when i print those values cookies are not displaying in browser.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script>
        function getData(){
            var input=document.getElementById("txtbox").value;
            //alert(input);
            setCookie("TextDetails", input);
            var TextDetails=getCookie("TextDetails");                                
            //document.write("your input deatails:"+TextDetails);
        }
        function getCookie(name) {
            var start = document.cookie.indexOf( name + "=" );
            var len = start + name.length + 1;
            if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
                return null;
            }
            if ( start == -1 ) return null;
            var end = document.cookie.indexOf( ";", len );
            if ( end == -1 ) end = document.cookie.length;
            return unescape( document.cookie.substring( len, end ) );
        }
        function setCookie(name, value) {
            var now = new Date();
            var time = now.getTime();
            time += 3600 * 1000;
            now.setTime(time);
            document.cookie = name+"=" + value + '; expires=' + now.toUTCString() + ';domain='+window.location.hostname+';path=/';
        }
    </script>
</head>
<body>
    <%
        out.println("<table><tr><td>");
        out.println("<input type='text' id='txtbox'>");
        out.println("<input type='button' value='go'onclick='getData()'>");
        out.println("</td></tr></table>");
    %>
</body>

when i put the comment line cative without comment in getData()function cookies are not storing but i need to print those cookies stored in browser.

2

There are 2 answers

0
LogPi On BEST ANSWER

You can try to use localStorage. It's better than Cookie when you need to store the data in client -side.

0
tajMahal On

In place of commented code //document.write("your input deatails:"+TextDetails); by writing this line document.getElementById("CookieDetail").innerHTML=TextDetails; create one dive in body with id CookieDetail.Now data will print as per our requirement.