我在网上找到了 [this][1],相当困难的 javascript 示例,我已经在我的网站上成功实现了它。
但是,在这种情况下,我想在一个新的文本字段中获得两个小计的结果。
传统的 getElementbyId
和 total.value=total
行不通。
编辑
function doMath()
{
// Capture the entered values of two input boxes
var twogiga = document.getElementById('twogig').value;
var fourgiga = document.getElementById('fourgig').value;
// Add them together and display
var sum = parseInt(twogiga) + parseInt(fourgiga);
document.getElementById('total').value = parseInt(sum);
}
这是我使用的 javascript。但由于某种原因,当我只有一个值 (twogig
) 时,total
设置为 NaN。我的脚本有什么问题?
最佳答案
好吧,如果你已经为文本输入分配了 ID,例如:<input type="text"id="my_input"/>,那么你可以使用 document.getElementById('my_input').value 来调用它。
所以:
<input type="text" id="my_input1" /> <input type="text" id="my_input2" /> <input type="button" value="Add Them Together" onclick="doMath();" /> <script type="text/javascript"> function doMath() { // Capture the entered values of two input boxes var my_input1 = document.getElementById('my_input1').value; var my_input2 = document.getElementById('my_input2').value; // Add them together and display var sum = parseInt(my_input1) + parseInt(my_input2); document.write(sum); } </script>
当然,这是一个非常基本的脚本,它不会检查以确保输入的值是数字。我们必须将字段转换为整数,否则它们将是字符串(因此 2+2 将等于 22)。单击按钮时,会调用该函数,该函数为每个输入框生成一个变量,将它们转换为整数,相加,并输出我们的总和。
关于javascript - 两个文本字段的总和 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462772/