0

What am I doing wrong? If this is a duplicated question, please redirect me to the correct question because I can't find anything about it.

It is that simple:

I get this error: "Uncaught TypeError: Cannot set property 'onclick' of null"

In this hyper-mega-ultra-easy piece of code:

window.onload = function() {
  document.write('<input id="a" type="button" value="This is a button :)">');
  document.getElementById("a").onclick = alert("a");
}

How can this even be possible? Regards.

  • 1
    Should work, but don't use document.write. https://stackoverflow.com/questions/2199949/add-event-to-button-with-javascript – wazz Jun 23 '18 at 23:22
  • 1
    Run the snippet. There is no such error. – CertainPerformance Jun 23 '18 at 23:33
  • 1
    That works, at least in the above snippet. When assign to `onclick` like that, it fires the `alert` when assigned. Instead wrap it in a function, e.g. `document.getElementById("a").onclick = function() { alert("a") };` – Asons Jun 23 '18 at 23:38
  • Also check out the note at the top of [this page](https://developer.mozilla.org/en-US/docs/Web/API/Document/write). – wazz Jun 23 '18 at 23:51

2 Answers2

0

Putting the code to run after the button is click into a function will make Javascript "connect" that function to the action from the user.

window.onload = function() {
       document.write('<input id="a" type="button" value="This is a button :)">');
       document.getElementById("a").onclick = function() {
          alert("a");
       };
    }

Otherwise, instead of creating a new function, you can use another one already defined in your code but setting the onclick event = to the function without the parenthesis as shown below.

function whenYouClick() {
 alert("a");
}

window.onload = function() {
document.write('<input id="a" type="button" value="This is a button :)">');
document.getElementById("a").onclick = whenYouClick;
}
Francesco
  • 429
  • 4
  • 12
-1

Instead of your code:

window.onload = function() {
  document.write('<input id="a" type="button" value="This is a button :)">');
  document.getElementById("a").onclick = alert("a");
}

You can use:

window.onload = function() {
  document.write('<input id="a" type="button" value="This is a button :)">');
  document.getElementById('a').setAttribute('onclick','alert(0)');
}