Reputation: 95
I've got an issue with addEventListener
.
var x = parseInt(document.getElementById("nb1").value);
var y = parseInt(document.getElementById("nb2").value);
document.getElementById("calculate").addEventListener("click", calculate(x, y));
function calculate(x, y) {
document.getElementById("result").value = x + y;
}
When I execute this code, the function calculate is directly called without me clicking the button "calculate". I really don't understand why, could you help please ?
Upvotes: 2
Views: 403
Reputation: 24955
When you say functionName(param1, param2)
, it will call that function and return its value. So when you assign it to event listener, you are assigning its return value. If you want to pass arguments while assigning, you should use bind
.
Note: This will only work once, since you are assigning value to x
and y
only once. @Rayon Dabre's answer is ideal way.
var x = parseInt(document.getElementById("nb1").value);
var y = parseInt(document.getElementById("nb2").value);
document.getElementById("calculate").addEventListener("click", calculate.bind(event, x, y));
function calculate(x, y) {
document.getElementById("result").value = x + y;
}
<input type="text" value="10" id="nb1" />
<input type="text" value="20" id="nb2" />
<button id="calculate">Calculate</button>
<input type="text" id="result" />
Upvotes: 0
Reputation: 36609
In provided snippet, value of total will never be the expected value as you are storing values of input
field initially not when using is clicking calculate
button.
To get the updated values, you need to get the values when click
event takes place.
Also note, addEventListener
expects second argument to be function expression. In your case you are invoking function calculate
which will be executed when particular line of code is executed. If you want to pass arguments in function expression then -> function(){ calculate(x, y); }
Try this:
document.getElementById("calculate").addEventListener("click", calculate);
function calculate() {
var x = parseInt(document.getElementById("nb1").value);
var y = parseInt(document.getElementById("nb2").value);
document.getElementById("result").value = x + y;
}
<input type="text" id='nb1'>
<input type="text" id='nb2'>
<br>
<input type="text" readonly id='result' placeholder='Result'>
<br>
<button id='calculate'>Calculate</button>
Upvotes: 2
Reputation: 36703
Use callback like function(){ calculate(x, y); }
, your code will immediately execute the calculate(x,y)
and won't wait for the event to fire.
var x = parseInt(document.getElementById("nb1").value);
var y = parseInt(document.getElementById("nb2").value);
document.getElementById("calculate").addEventListener("click", function(){ calculate(x, y); });
function calculate(x, y) {
document.getElementById("result").value = x + y;
}
Upvotes: 1