How to write cookies in form input values with javascript?

Viewed 55

I have to use simple cookies for my school project. I tried to put form input values in cookies and I want them displayed once I refresh or submit page. Any other use of cookies is welcome but keep it simple. I searched this site through and I couldn't find an answer on my own.

This is my code:

<html>
    <head>
    <script>
    function setCookie()
    { 
        document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
    }

    function putCookie() {
        setCookie("Name", document.myForm.fn.value);
        return true;
    }

    function readCookie(cname) {
      var name = cname + "=";
      var ca = decodedCookie.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 "";
    }
    function checkCookie()
    {
        var user = getCookie("username");
        if (user != "")
        {
            alert("Welcome again " + user);
        }
    }
    function uradi(){
      let x = readCookie('Name');
      let target=document.getElementsByName("fn");
      if (x) {
        target.value=x;
      }
    }
    </script>
    </head>
    <body onload="uradi()">
       <div id="div1"><img class="slika1"src="port.jpg"></div>
       <div class="topnav">
        <a href="java1.html"><img class="navigacioni" src="experiment.png" alt="Experimet" id="item"></a>
        <a href="kontakt.html"><img class="navigacioni" src="know.png"></a>
        <a href="shop.html"><img class="navigacioni" src="shop.png"></a>
      </div>

      <div class="formasty">
        <form name="myForm" id="form">
          <p>First name:</p> 
          <input required name="fn" type="text" id="first_name"placeholder="First name..."  value=""/>
          <br>
          <input type="button"  onclick="putCookie()" id="dugme" value="Remember me">
        </form>
      </div>
    </body>
</html>
0 Answers
Related