问题描述
我在网上找到了 [this][1],相当困难的 javascript 示例,并且我已经在我的网站上成功实现了它.
但是,在这种情况下,我想获得一个新文本字段中两个小计的结果.
传统的 getElementbyId
和 total.value=total
不起作用.
编辑
函数 doMath(){//捕获两个输入框的输入值var twogiga = document.getElementById('twogig').value;var Fourgiga = document.getElementById('fourgig').value;//将它们相加并显示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="把它们加在一起" onclick="doMath();"/><script type="text/javascript">函数 doMath(){//捕获两个输入框的输入值var my_input1 = document.getElementById('my_input1').value;var my_input2 = document.getElementById('my_input2').value;//将它们相加并显示var sum = parseInt(my_input1) + parseInt(my_input2);document.write(sum);}当然,这是一个非常基本的脚本,它不会检查以确保输入的值是数字.我们必须将字段转换为整数,否则它们将是字符串(因此 2+2 将等于 22).当按钮被点击时,该函数被调用,它为每个输入框创建一个变量,将它们转换为整数,将它们相加,然后输出我们的总和.
I found [this][1], rather difficult, javascript example online and I've implemented it with success in my website.
However, I would like to get the result of, in this case, the two subtotals in one new text-field.
The traditional getElementbyId
and total.value=total
didn't work out.
EDIT
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);
}
This is the javascript I use. But for some reason, when I have just one value (twogig
), the total
is set as NaN. What is wrong with my script?
Well, if you have assigned ID's to text inputs, for example: <input type="text" id="my_input" />, then you can call it with document.getElementById('my_input').value.
So:
<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>
Naturally, that is a very basic script, it doesn't check to make sure the entered values are numbers. We have to convert the fields into integers, otherwise they'll be strings (so 2+2 would equal 22). When the button is clicked, the function is called, which makes a variable for each input box, converts them to ints, adds them, and outputs our sum.
这篇关于两个文本字段的总和 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!