javascriptdom

Why Won't my JS Code Run?


For some reason I am getting this issue: Uncaught TypeError: Cannot read property 'value' of null on the document.getElementById line. What is the issue?? I have no clue.

HTML Code:

<html>
<head>
<title>I am a chrome extension</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script src="scripts.js"></script>
</head>
<body bgcolor="#34495e">
 <div class="login-card">
    <h1>Please Enter Your Birthday</h1><br>
  <form>
    <input type="date" name="user" placeholder="Username">
    <input type="submit" id="age" name="submit" class="login login-submit" value="Submit">
  </form>
  </div>
</body> 
</html>

scripts.js

function getAge()
{
    var age = document.getElementById("age").value;
    console.log(age);

}
document.getElementById('age').onclick = getAge();

Solution

  • Using parentheses after a function invokes the function. To bind the event to the function simply reference getAge without parentheses, like this:

    document.getElementById('age').onclick = getAge;
    

    You should also be sure to wait until after the DOM is completely loaded using the onload event. You should also take time to carefully read properly bind javascript events.