I'm relatively new to JS, but I have programmed in C before, and I'm trying to get my head around the whole event driven nature of it. I'm trying to create a script that will validate form input, however all of my code is being run - everything inside if/else, loops, what have you - regardless of the event happening or not. To test, and to make it easier to post here, I've written a simple program that has this problem too.
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 the alert should pop up when the button with the ID "test" is clicked (onclick). What is actually happening is that the alert is popping up as soon as the page loads, and will pop up again if I hit the button.
My thinking is that I've made some incorrect assumptions about the order in which JS is executed, but I cant think of what that is. Is anyone able to shed some light on this?