Reputation: 1162
I am having trouble passing input values into a JavaScript function that takes two values and multiplies them. When I hard-code my numbers in, it works just fine. But, when I try to use the input values, I don't get anything - not even undefined
. Here's my code:
function multiply (val1, val2) {
var n = val1;
for(var i = 1; i < val2; i++) {
n += val1;
}
return n;
}
var result = multiply(document.getElementById('first').value, document.getElementById('second').value);
document.getElementById('result').innerHTML = result;
<h1>Mutiplication Algorithm</h1>
<p>This algorithm attempts to multiply to given values without ever using the <span>*</span> operator</p>
<input id="first" type="text" value=5 /> x
<input type="text" value=4 /> =
<span id="result"></span>
Thanks!
Upvotes: 0
Views: 40
Reputation: 498
Please review your code again. You didn't have your second input id parameter. Then if you want to treat values as integers, simply parse them as int :) Look at code below
function multiply (val1, val2) {
val1 = parseInt(val1);
var n = val1;
for(var i = 1; i < val2; i++) {
n += val1;
}
return n;
}
var result = multiply(document.getElementById('first').value, document.getElementById('second').value);
document.getElementById('result').innerHTML = result;
<h1>Mutiplication Algorithm</h1>
<p>This algorithm attempts to multiply to given values without ever using the <span>*</span> operator</p>
<input id="first" type="text" value=5 /> x
<input type="text" id="second" value="4" /> =
<span id="result"></span>
Upvotes: 2