I am trying to do a simple calculation of two numbers that lets the user either multiply them or divide them. I know there are other ways do do this with way less code but I'd like to figure out why my result box is displaying NaN. I've tested to make sure the userInput1 and userInput2 variables are both indeed numbers but it looks like something is happening inside the other functions to make it NaN.`
/*eslint-env browser*/
var $ = function(id) {
"use strict";
return window.document.getElementById(id);
};
var userInput1 = parseInt($('input1'), 10);
var userInput2 = parseInt($('input2'), 10);
//TO TEST
console.log(typeof userInput1);
console.log(typeof userInput2);
function doTheMultiCalc() {
"use strict";
var multiCalculation = userInput1 * userInput2;
//TO TEST
console.log(typeof(multiCalculation));
$('resultOutput').value = multiCalculation;
return multiCalculation;
}
function doTheDivCalc() {
"use strict";
var divCalculation = userInput1 / userInput2;
//TO TEST
console.log(typeof(divCalculation));
$('resultOutput').value = divCalculation;
return divCalculation;
}
//Event Handler Function
function init() {
"use strict";
$('multiply').addEventListener('click', doTheMultiCalc);
$('divide').addEventListener('click', doTheDivCalc);
}
window.addEventListener('load', init);
<label for="input1">1st Number</label><input id="input1"><br>
<label for="input2">2nd Number</label><input id="input2"><br>
<button id="multiply" type="button">Multiply</button>
<button id="divide" type="button">divide</button><br>
<label for="resultOutput">Result is</label> <input id="resultOutput">
`
I commend your trying to figure this out. So there are two issues I see.
First and foremost, you're not actually getting the value of the inputs. You need to use $('input1').value
to retrieve the actual value of the input.
You also need to fetch that value before doing each operation. Here you see it in action:
/*eslint-env browser*/
var $ = function(id) {
"use strict";
return window.document.getElementById(id);
};
function doTheMultiCalc() {
"use strict";
var userInput1 = parseInt($('input1').value, 10);
var userInput2 = parseInt($('input2').value, 10);
var multiCalculation = userInput1 * userInput2;
$('resultOutput').value = multiCalculation;
return multiCalculation;
}
function doTheDivCalc() {
"use strict";
var userInput1 = parseInt($('input1').value, 10);
var userInput2 = parseInt($('input2').value, 10);
var divCalculation = userInput1 / userInput2;
$('resultOutput').value = divCalculation;
return divCalculation;
}
//Event Handler Function
function init() {
"use strict";
$('multiply').addEventListener('click', doTheMultiCalc);
$('divide').addEventListener('click', doTheDivCalc);
}
window.addEventListener('load', init);
<label>1st Number</label><input id="input1"><br><br>
<label>2nd Number</label><input id="input2"><br><br>
<button id="multiply">Multiply</button>
<button id="divide">divide</button><br><br>
<label>Result is</label> <input id="resultOutput">