Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to create cookie with the help of JavaScript ?

How to create cookie with the help of JavaScript ?

A cookie is an important tool as it allows you to store the user information as a name-value pair separated by a semi-colon in a string format. If we save a cookie in our browser then we can log in directly to the browser because it saves the user information.

Approach: When a user sends the request to the server then the cookie tells that this user is already logged in your browser and the server recognizes the user and allows the user to log in. We can apply various operations on cookie-like create, delete, read, add an expiry date to it so that users can never be logged in after a specific time. A cookie is created by the document.cookie keyword as shown below.

Example: In the below example, we will take input from the user as a name for the cookie and store it in cookievalue. Then cookievalue is stored in string format adding the ‘name’ attribute and then the cookie is created in the browser.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <form name="myform" action="">
        Enter name:
        <input type="text" name="customer" />
        <input type="button" value="Set Cookie" 
            onclick="WriteCookie();" />
    </form>
  
    <script type="text/javascript">
        function WriteCookie() {
            if (document.myform.customer.value == "") {
                alert("Please enter value");
                return;
            }
            cookievalue = escape(
                document.myform.customer.value) + ";";
  
            document.cookie = "name=" + cookievalue;
              
            document.write("Setting Cookies : " 
                + "name=" + cookievalue);
        }
    </script>
</body>
  
</html


Output:

Adding an expiry date (in UTC): We can add expire date for the cookie to ensure that after that time the cookie will no longer be in use.

Syntax:

document.cookie = "username=neveropen; 
expires=Sun, 16 JAN 2022 12:00:00 UTC";

Deleting the Cookie: When you want to delete the cookie just simply set the expires parameter and leave the username blank.

document.cookie = "username=; 
expires=Sun, 16 JAN 2022 12:00:00 UTC";

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments