Javascript: functions are called when the page loads instead of onclick / onsubmit

I am relatively new to JS, but I programmed it in C before and I am trying to draw attention to this whole event. I am trying to create a script that will check the input of a form, however, all my code runs - everything inside the if / else loop, what you have - regardless of event or not. To test and facilitate shipping here, I wrote a simple program that also has this problem.

HTML:

<button id="test">Test</button> 

JavaScript:

 function init(){ document.getElementById("test").onclick = alert("hello"); } window.onload = init; 

From what I understand, the init function should be called when the page loads (window.onload), and a warning appears when the button with the identifier "test" is pressed (onclick). In fact, what happens is that the warning appears as soon as the page loads, and will reappear if I press the button.

My thinking is that I made some incorrect assumptions about the order in which JS is executed, but I cannot think what it is. Can anyone shed some light on this?

+6
source share
2 answers

It is not, it should be:

 function init(){ document.getElementById("test").onclick = function () { alert("hello"); }; } 

This is because you need JavaScript, you need to assign the function to the click event itself (warning is a function).

Take this for example:

 function hello() { alert("hello"); } document.getElementById("test").onclick = hello; 

Please note that after hello I did not put the brackets () ? This is because I use the link to the function itself. If I put the brackets, I actually evaluate this function at the point in time when the click assignment occurs.

So:

 document.getElementById("test").onclick = hello(); 

Indicates that after this line alert will be displayed immediately .

+10
source

yes, your javascript function will only call when the page loads. If you also want to call this init () function when you click the Test button, please try like this:

JavaScript:

 function init(){ alert("hello"); } window.onload = init; 
 HTML: <button id="test" onClick='init()'>Test</button> 
+1
source

Source: https://habr.com/ru/post/986351/


All Articles