Why is this javascript not working in html, but is working in console?

This is my html, and it does not seem to add this cookie.

<?php
  $cookie_name="user";
  $cookie_value="anony";
  setcookie($cookie_name, $cookie_value, time() + (86400 * 7), "/");
?>

<script>
  function ChangeCookie(loginuser){
    document.cookie = "user="+ loginuser +"; expires=Thu, 18 Dec 2018 12:00:00 UTC; path=/";
    return 1;
  }
</script>

<html>
  <head>
    <title>Login</title>
  </head>
  <body>
    Please enter your username
    <form name="myForm" action="/index.html" onsubmit="return ChangeCookie(document.GetElementById("user"))" method="post">
      <input type="text" id="user">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

If I directly do:

function ChangeCookie(loginuser){
document.cookie = "user="+ loginuser +"; expires=Thu, 18 Dec 2018 12:00:00 UTC; path=/";
  return 1;
}

In the console, it adds the cookie just fine.

I do not actually know what is going on, but I need this for a pretty big project. I have tried to do every single thing on my mind, but there is nothing that I could do that would change this feature.

Upvotes: 0

Views: 79

Answers (1)

JK4599
JK4599

Reputation: 94

Three things you need to fix here to get it working.

  1. change GetElementById to getElementById
  2. proper use of quotes around user. User single quotes instead of double as you are using double quotes for the entire onsubmit function.
  3. you need to pass value of the input field instead of the input element itself. You can do this by document.getElementById('user').value

Upvotes: 2

Related Questions