我正在尝试创建一个自动对模糊输入字段求和的表单,并在非活动状态中显示总和"总计:"领域。如果用户将焦点放在输入中,然后在不输入任何内容的情况下移开焦点,并且如果用户确实输入了我想要将字段限制为仅数字的内容,则我不想运行任何内容。如果有更好的方法,请告诉我。以下是我目前的方法示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Calc</title>
<script src="javascript.js"></script>
</head>
<body>
<h1>Sales By Month</h1>
<form method="get">
<label for="january">January:</label>
<input type="text" id="january" class="amount" onblur="isNum(); calculateSum();">
<label for="february">February:</label>
<input type="text" id="february" class="amount" onblur="isNum(); calculateSum();">
<label for="total">Total:</label>
<input type="text" id="total" disabled>
</form>
</body>
</html>
function calculateSum() {
var elems = document.getElementsByClassName('amount');
var myLength = elems.length;
sum = 0;
for (var i = 0; i < myLength; ++i) {
sum += elems[i].value *1;
}
document.getElementById('total').value = sum;
}
function isNum() {
var amounts = parseInt(document.getElementsByClassName('amount').value);
if (isNaN(amounts) == true && amounts != '') {
alert("Please enter a numeric value");
}
}
计算功能目前有效,但&#34;请输入数值&#34;无论内容如何,每当我离开某个字段时都会弹出警报。
答案 0 :(得分:1)
首先你需要测试失去焦点的元素的值,这意味着你应该在这样的参数中传递它
onblur="isNum(this); calculateSum();"
然后在你的isNum
函数中使用javascript删除document.getElementsByClassName
并使用参数代替...并且不要测试amounts != ''
是否因为它永远不会等于空字符串执行此操作amounts = parseInt(elem.value);
时,您必须在elem.value
function isNum(elem)
{
var amounts = parseInt(elem.value);
if (isNaN(amounts) == true && elem.value != '') {
alert("Please enter a numeric value");
}
这是 jsFiddle