Search code examples
javascriptformscookiessetcookie

Set cookies from html form


I try to set cookies from my html form wit onsubmit event. But console return "Uncaught ReferenceError: setCookies is not defined"

This is a piece of my code:

<form action="page.html" method="POST" onsubmit=" return setCookies(this)" id="myFormId">
      <input name='user' placeholder='user'><br>
      <input name='password' type='password' placeholder='password'><br>
      <button type='submit'>Try</button>
    </form>
    <h1>HWETEYT</h1>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
    var setCookies = (function(form){
          console.log(form[0].value)
          for (i = 0; i < form.length; i++){
            document.cookie = form[i] + "=" + form[i].value;
          }
          console.log(document.cookie);
        }
      });
    </script>

I try make my function as a global but result the same.


Solution

  • Since you have added the src attribute to the script tag, the code written inside is ignored. Thus you have to split the script as two scripts;

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    
    
    <script>
    var setCookies = function(form){
          console.log(form[0].value)
          for (i = 0; i < form.length; i++){
            document.cookie = form[i] + "=" + form[i].value;
          }
          console.log(document.cookie);
        }
    </script>