0

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();

3 Answers3

1

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.

Community
  • 1
  • 1
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

Because you're including the script in the head, and it loads before the dom elements do. You'll need to apply pswg's answer as well.

The way to fix this is simply use window.onload

window.onload = function () {
    document.getElementById("age").onclick = getAge;
}
agmcleod
  • 13,321
  • 13
  • 57
  • 96
  • It works, but how come the stuff appears in the console for like a blink and disappears, why is that? – user3911017 Aug 16 '14 at 02:28
  • 1
    @user3911017 Your event should return false / call preventDefault if you'd like to cancel the browser's default behavior of clicking a link. See also [event.preventDefault() vs. return false](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – p.s.w.g Aug 16 '14 at 02:34
0

This is because you include you js file in the head, before your actual html gets evaluated. You cant getElementById because the element is not there yet!!

generally, js files are include at the bottom, right above the closing body tag. To make sure, use document.onload();