将两个输入与JavaScript和&在文本框中显示 [英] Multiplying two inputs with JavaScript & displaying in text box
问题描述
我是JavaScript&我正在寻找一些帮助做两个数字的简单乘法&在另一个文本框中显示结果。我一直试图让这个工作好几天无济于事:(
I am new to JavaScript & am looking for some help doing simple multiplication of two numbers & displaying the result in another text box. I have been trying to get this working for days to no avail :(
这里是基本的HTML以及JavaScript和这里的小提琴的链接 http://jsbin.com/egeKAXif/1/edit
Here is the basic HTML along with the JavaScript & a link to a fiddle here http://jsbin.com/egeKAXif/1/edit
我做错了什么?
我想写的应用程序至少有12行,我如何扩展JavaScript / HTML以适应这种情况?每个输入标识符是否必须是唯一的?
The application I want to write will have at least 12 rows, how would I extend the JavaScript / HTML to accommodate this? Would each input identifier need to be unique?
任何帮助表示赞赏:)
<table width="80%" border="0">
<tr>
<th>Box 1</th>
<th>Box 2</th>
<th>Result</th>
</tr>
<tr>
<td><input id="box1" type="text" /></td>
<td><input id="box2" type="text" onchange="calculate()" /></td>
<td><input id="result" /></td>
</tr>
</table>
<script>
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var result = document.getElementById('result');
var myResult = box1 * box2;
result.innerHTML = myResult;
}
</script>
推荐答案
首先要改变的是线路随着乘法。它应该是: var myResult = myBox1 * myBox2;
The first thing you have got to change is the line with the multiplication. It should be: var myResult = myBox1 * myBox2;
你不应该将innerHTML与输入字段一起使用 - 使用值。
You should not use innerHTML with input fields - use value.
除此之外, onchange
事件仅在输入失去焦点时触发。您可能希望使用 oninput
事件。
Additional to that, the onchange
event fires only when the input looses the focus. You might want to use the oninput
event.
查看工作示例: http://jsbin.com/OJOlARe/1/edit
这篇关于将两个输入与JavaScript和&在文本框中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!