Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix this "Onclick function does not work "

let username;
document.getElementById("mySubmit").onclick= function(){
  username= document.getElementById("myText").value;
document.getElementById("myH1").textContent= `Hello ${username}`

}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="4style.css">
</head>
<body>
  <script src="4userinput.js"></script>

  <h1 id="myH1">Welcome</h1>
<label>user name:</label>
<input id="myText"> 
<br>
<br>
<button id="mySubmit">Submit</button>
</body>
</html>

When i run code it gave me this error:
4userinput.js:10 Uncaught TypeError: Cannot set properties of null (setting ‘onclick’)

Can someone help me with this problem. My code works well in the stackoverflow snippet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is due to the JavaScript code executing before the DOM elements are fully loaded, since the script is included before the button even exists. Moving the <script> tag to the end of the <body> section, should resolve the problem :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="4style.css">
</head>
<body>
  

  <h1 id="myH1">Welcome</h1>
<label>user name:</label>
<input id="myText"> 
<br>
<br>
<button id="mySubmit">Submit</button>


<!-- Move it here -->
<script src="4userinput.js"></script>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading