10

I am creating an HTML page, Which is built using bootstrap. Here is the final HTML code and code of hello.js file:

document.getElementById("subm").onclick = function () {
  alert("Hello WOrld");
}
<!DOCTYPE html>
<html>
<head>
  <title>Calculator</title>
  <link rel="stylesheet" href="/stylesheets/style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
</html>
<body>
  <link rel="stylesheet" href="/stylesheets/bootstrap.min.css">
  <script src="http://code.jquery.com/jquery.js"></script>
  <script src="javascripts/bootstrap.min.js"></script>
  <script src="javascripts/hello.js"></script>
  <h1>Calculator</h1>
  <form class="form-horizontal center1">
    <div class="control-group">
      <label for="num1" class="control-label">Number1</label>
      <div class="controls">
        <input id="num1" type="number" placeholder="Enter an Integer">
      </div>
    </div>
    <div class="control-group">
      <label for="num2" class="control-label">Number2</label>
      <div class="controls">
        <input id="num2" type="number" placeholder="Enter an Integer">
      </div>
      <div class="control-group">
        <label for="options" class="control-label">Options</label>
        <div class="controls"><br>
          <select id="options">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
          </select>
        </div>
      </div>
      <div class="control-group">
        <div class="controls"><br>
          <button id="subm" type="submit" class="btn">Calculate</button>
        </div>
      </div>
      <div class="control-group">
        <div class="controls">
          <input id="cal" type="text" placeholder="Calculator output" disabled="true">
        </div>
      </div>
    </div>
  </form>
</body>

When I click on the button using submit then instead of alert I am getting error

Uncaught TypeError: Cannot set property 'onclick' of null

Can anyone please tell me why I am facing this error?? Help to resolve it.

user9088454
  • 1,018
  • 1
  • 11
  • 34
Ritesh Mehandiratta
  • 6,595
  • 28
  • 114
  • 186

5 Answers5

26

The problem seems to be you are executing the script before the element is loaded.

I assume this script is added in the hello.js file which is added before the DOM is created.

The solution here is to execute the script after the DOM is ready like:

window.onload = function(){
    document.getElementById("subm").onclick=function(){
        alert("Hello WOrld");
    }
}

All JavaScript code which deals with DOM elements like the one above has to be executed only after the DOM is loaded.

Demo: Fiddle

Nisse Engström
  • 4,555
  • 22
  • 24
  • 38
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
  • 1
    Another possible work around could be to move `` to bottom of the page – Arun P Johny Jun 13 '13 at 06:31
  • ok i got ur point i make my javascript file to document.onload = function() {document.getElementById("subm").onclick=function(){ alert("Hello WOrld"); } } but when i clicked on the button its not showing alert why can u figure it out plz!! – Ritesh Mehandiratta Jun 13 '13 at 06:33
  • @RiteshMehandiratta change it into `window.onload` – Arun P Johny Jun 13 '13 at 06:38
  • Is it considered good practice to move script tag to the bottom of the page ? Does it have any effect on performance or loading ? – 0decimal0 Mar 28 '18 at 19:33
5

window.onload() didn't solve my problem so i had to write code to wait for the element to get loaded. You can do something like this:

function waitForLoad(id, callback){
    var timer = setInterval(function(){
        if(document.getElementById(id)){
            clearInterval(timer);
            callback();
        }
    }, 100);
}

waitForLoad("subm", function(){
    console.log("load successful, you can proceed!!");
    document.getElementById("subm").onclick = function()
    {
        alert("I got clicked");
    }
});
codemania23
  • 868
  • 9
  • 18
  • "window.onload() didn't solve my problem" — Then you had a different problem to the one that this question is asking about. There's nothing delaying the loading of the element that the OP is trying to access. – Quentin May 19 '17 at 08:26
  • window.onload doesn't work in all scenarios because you have other frameworks overriding the standard window. I'm trying to help people who navigate to this page by adding another answer. Consider my example, I'm using an angular js framwork where window.onload doesn't work so if it's helpful, there is no need to downvote an answer – codemania23 May 19 '17 at 08:31
  • Also, Code Lovers answer is the same as my answer the only difference is that he used jquery and my solution is in standard javascript. So, why the hate ? – codemania23 May 19 '17 at 08:32
  • 1
    This was exactly what worked for me! none of the window.onloads etc. Thanks a lot – Tejas Jaggi Feb 02 '20 at 04:31
  • Welcome Tejas :D. – codemania23 Feb 03 '20 at 13:10
4

As I see you are using the JQuery then use the jQuery's function why are you using javascript.

Here is the code for you desire:

$(document).ready(function(){
  $("#subm").click(function(){
      alert("Hello World");   
  });
});
Code Lღver
  • 15,171
  • 16
  • 51
  • 71
3

It is probably happening because the script runs before the DOM loads.

Try putting the script in

window.onload = function() {
   {your code}
}
JNF
  • 3,626
  • 3
  • 26
  • 62
1

I had got a similar problem...For me it worked with following code

$(document).on('click','#subm',function() {
    alert("Hello World");
});    
Ngenator
  • 9,706
  • 3
  • 36
  • 43
user2427829
  • 108
  • 7