user3911017
user3911017

Reputation: 3

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

Upvotes: -1

Views: 1439

Answers (3)

user3889625
user3889625

Reputation: 13

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

Upvotes: 0

agmcleod
agmcleod

Reputation: 13611

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;
}

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 148980

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.

Upvotes: 1

Related Questions