Began to study JS, faced with such a problem

function result(){ var zerc = document.getElementsByTagName("INPUT").value; if (zerc == ''){ zerc == '0'; } } document.getElementById("btn").onclick = result(); // Ошибка Uncaught TypeError: Cannot set property 'onclick' of null 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Zero</title> <script src="js/zerocount.js"></script> </head> <body> <input type="number"> <br><br> <input type="number"> <br><br> <input type="number"> <br><br> <input type="number"> <br><br> <input type="number"> <br><br> <input type="number"> <br><br> <input type="number"> <br><br> <input type="number"> <br><br> <input id="btn" type="button" value="0" onclick="result()"> </body> </html> 

  • one
    First, the array of elements has no value. Secondly, apparently, your script runs before the btn appears in the html-code - andreymal
  • Third, for some reason you are shoving in onclick not a function, but the result of a function call, that is, undefined - andreymal

2 answers 2

 function result(){ var input = document.getElementsByTagName("INPUT"); for (var i = 0; i < input.length; i++) { if (input[i].value == ''){ input[i].value = '0'; } } } document.getElementById("btn").onclick = result; 

In general, it is worth using placeholder for such cases.

  • Thanks for the fix, skipipastil and did not notice the error. - Curious

To do this, you need to set the html element with the placeholder attribute with the desired value.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Zero</title> <script src="js/zerocount.js"></script> </head> <body> <input type="number" placeholder="0"> <br><br> <input id="btn" type="button" value="0" onclick="result()"> </body> </html>