简体   繁体   中英

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

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM