0

When i click on the button, nothing happens. Firebug says that "TypeError: btnNew is null"

My Javascript code is:

function addNewItem(){
alert("Test")
};

var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;

And the html is:

<input type = "text" id = "input">
<button id = "btnAdd">New item</button>

How come btnNew is null if its value is document.getElementById("btnAdd") ?

kamokoba
  • 497
  • 9
  • 17

2 Answers2

2

function addNewItem(){
  alert("Test")
}


window.onload = function() {
  var btnNew = document.getElementById("btnAdd");
  btnNew.onclick = addNewItem;
}
<input type = "text" id = "input">
<button id = "btnAdd">New item</button>

You have to execute your js code after the document is loaded.

In window.onload or $document.ready() if you use jquery.

See window.onload vs $(document).ready() for differences.

Community
  • 1
  • 1
Thierry
  • 5,133
  • 3
  • 25
  • 30
  • 1
    Simply loading or locating the script at the bottom of the page (just before the closing body tag) is also usually enough to ensure that the element is present in the DOM and ready for interaction. There is also the DOMContentLoaded event (https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) which can be used (where supported) if jQuery is not available for desirable. – pwdst Jan 20 '15 at 20:34
0

you could use body onload event

see the code bellow

<!DOCTYPE html>
<html>
<body onload="myFunction()">

<input type = "text" id = "input">
<button id = "btnAdd">New item</button>

<script>
function myFunction() {
   function addNewItem(){
alert("Test")
};

var btnNew = document.getElementById("btnAdd");
btnNew.onclick = addNewItem;
}
</script>

</body>
</html>
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30