将输入值传递给JavaScript函数

时间:2017-05-10 21:10:49

标签: javascript forms

我无法将输入值传递给JavaScript函数,该函数接受两个值并将它们相乘。当我对我的数字进行硬编码时,它的工作正常。但是,当我尝试使用输入值时,我什么也得不到 - 甚至不是undefined。这是我的代码:

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>

谢谢!

1 个答案:

答案 0 :(得分:2)

请再次检查您的代码。你没有第二个输入id参数。然后,如果要将值视为整数,只需将它们解析为int :)查看下面的代码

&#13;
&#13;
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;
&#13;
<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>
&#13;
&#13;
&#13;