0

I have been trying to display the sum with console.log, it seems not to be working. Can anyone assist?

var result = document.getElementById('result');
var firstNum = document.getElementById('number1');
var secondNum = document.getElementById('number2');

firstNum.addEventListener('keyup', sum);
secondNum.addEventListener('keyup', sum);

function sum(e){

    var mySum = firstNum + secondNum;
    console.log(mySum);
}
Tobi Id
  • 33
  • 4
  • 1
    You need to: get the value, not the HTMLElement (`.value`), get it the moment the event listener fires, not globally once at start of evaluation, and convert to number, as inputs have string values. – ASDFGerte Feb 06 '22 at 14:22
  • 1
    firstNum and secondNum are html elements (inputs probably) you can't add inputs but only their `.values`s (if you convert them to numbers correctly) – derpirscher Feb 06 '22 at 14:23
  • 1. `firstNum` is an HTML element, not a value. You can't sum it. [Use `.value`](https://stackoverflow.com/questions/4173391/getting-dom-element-value-using-pure-javascript) 2. The result is a string, you need to [convert to a number](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum). – VLAZ Feb 06 '22 at 14:24

1 Answers1

1

Assuming that firstNum and secondNum are input fields you would need to get the value of these inputs. Input values are string so you also would need to cast the values to numbers.

var result = document.getElementById('result');
var firstNum = document.getElementById('number1');
var secondNum = document.getElementById('number2');

firstNum.addEventListener('keyup', sum);
secondNum.addEventListener('keyup', sum);

function sum(e){

    var mySum = Number(firstNum.value) + Number(secondNum.value);
    console.log(mySum);
}
Palladium02
  • 1,134
  • 1
  • 4
  • 13