crescentfresh crescentfresh - 2 years ago 129
Javascript Question

Why is my function outputting 0 (zero)?

This code is supposed to calculate two user inputs by multiplying them. However, the output is consistently 0 instead of would normally be expected ie 5*5=0. I am not sure why this is happening. Am I not passing the variables into the function correctly? I feel like I might not be properly understanding value vs. reference (I am currently learning javascript)

var x = document.getElementById("a").value;
var y = document.getElementById("b").value;
var button = document.getElementById("button");

button.addEventListener('click', function() {
}, false);

function calculator(a,b) {
var output = a * b;
document.getElementById("answer").innerHTML = output;

Answer Source

Omit the value capture, just grab the elements:

var x = document.getElementById("a");
var y = document.getElementById("b");

Then use the values as the function parameters.

button.addEventListener('click', function() {
  calculator(x.value, y.value);
}, false);

You were grabbing the values when they were empty and passing those to the function.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download