键入时自动计算加法和子转换 [英] auto calculate addition and subtranstion while typing
本文介绍了键入时自动计算加法和子转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<html>
<body>
<form>
Addition 1:<br>
<input type="text" name="add1">
<br>
Subtraction 1:<br>
<input type="text" name="sub1">
<br>
Addition 2:<br>
<input type="text" name="add2">
<br>
Subtraction 2:<br>
<input type="text" name="sub2"><br> <br>
<label>Total</label>
<input type="text" name="total" disabled>
</form>
</body>
</html>
推荐答案
这里是一个示例:
HTML代码:
Here is an example :
Html code :
<div>
Addition 1:<br />
<input type="text" id="add1" name="add1" onkeyup="AutoCalc(this)" />
<br />
Subtraction 1:<br />
<input type="text" id="sub1" name="sub1" onkeyup="AutoCalc(this)" />
<br />
Addition 2:<br />
<input type="text" id="add2" name="add2" onkeyup="AutoCalc(this)" />
<br />
Subtraction 2:<br />
<input type="text" id="sub2" name="sub2" onkeyup="AutoCalc(this)" />
<br />
<br />
<label>
Total</label>
<input type="text" id="total" name="total" disabled="disabled" />
</div>
和Javascript:
And Javascript :
function AutoCalc(obj) {
var total = 0;
if (isNaN(obj.value)) {
alert("Please enter a number :(");
obj.value = '';
return false;
}
else {
var textBox = new Array();
textBox = document.getElementsByTagName('input')
for (i = 0; i < textBox.length; i++) {
if (textBox[i].type == 'text') {
var inputVal = textBox[i].value;
if (inputVal == '')
inputVal = 0;
if ((textBox[i].id == 'add1') || (textBox[i].id == 'add2')) {
total = total + parseInt(inputVal);
}
if ((textBox[i].id == 'sub1') || (textBox[i].id == 'sub2')) {
total = total - parseInt(inputVal);
}
}
}
document.getElementById('total').value = total;
}
}
希望对您有帮助.
Hope it helps you.
这篇关于键入时自动计算加法和子转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文