Reputation: 201
I am trying to create an onclick event(javascript), what takes input data from an HTML form, by pressing a button. I am using a window.onload function in my JS file. My form looks like:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" name="fhours"><br>
<span>Minutes: </span><input type="text" name="fminutes"><br>
<span>Seconds: </span><input type="text" name="fseconds"><br>
<input type="button" id="send" value="Enter">
</form>
My onclick event:
document.getElementById("send").addEventListener("click",setTheClockByButton());
and my setTheClockByButton():
function setTheClockByButton() {
alert("wtf");
setTheClock(setHour, setMinute, setSecond);
}
and when I press view in google chrome,the alert with the wtf comes up, so it seems my button is clicked by "itself", and I got no clue why :(
Upvotes: 0
Views: 107
Reputation: 2719
Remove the parenthesis in setTheClockByButton()
, when you create a function you are actually setting a variable. The long hand for creating a function looks like this.
var functionName = function() {
//Your code here
};
Therefore to assign a function to a handler, you must use the functions variable name, but to call the function you add the parenthesis. In this case you need simply the variable name so it would look like this.
document.getElementById("send").addEventListener("click",setTheClockByButton);
Upvotes: 2
Reputation: 3618
Remove the parenthesis in setTheClockByButton()
such as :
document.getElementById("send").addEventListener("click",setTheClockByButton);
It doesn't work because with those parenthesis you are calling the function instead of binding it to the event.
For more details about basic usage of addEventListener
you can have a look here.
Upvotes: 0
Reputation: 70075
You are executing setTheClockByButton()
when you set the event listener. Leave off the ()
.
document.getElementById("send").addEventListener("click",setTheClockByButton);
Upvotes: 0