Computer >> Computer tutorials >  >> Programming >> Javascript

How to use JavaScript to set cookies for a specific page only?


To set cookies for a specific page, you need to use the “window.location.pathname” property. The property returns the path and filename of the current page.

Example

You can try to run the following code to implement cookies for a specific page −

Live Demo

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";
               var myPath = window.location.pathname;

               document.cookie="name=" + cookievalue + ";path=myPath";
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type="text" name="customer"/>
         <input type = "button"  value = "Set Cookie"  onclick = "WriteCookie();"/>
      </form>
   </body>
</html>