使用 paying_now
输入字段的值调用我的 Javascript 函数 aa()
。我想找到 paying_now
和 paid
的值之和,以及 balance
和 paying_now
的差值.
netpay
、balance
和 paid
的值将从数据库中获取。在这里,我将 net_pay
设置为 1000,作为示例。
此代码仅适用于余额,并且在应向其中添加 paying_now
值时不会更改 paid
文本框。 NaN 也会发生。给出了什么?
Javascript
function aa(paying_now)
{
var net_pay = document.getElementById('net_pay').value;
var paid = document.getElementById('paid_hidden').value;
var balance = document.getElementById('balance_hidden').value;
if(parseInt(paying_now) > parseInt(net_pay))
{
document.getElementById('paying_now').value=0;
document.getElementById('paid').value=paid;
document.getElementById('balance').value=balance;
alert("Amount Paying now cannot be higher than Netpay");
return;
}
else if(parseInt(paying_now) > parseInt(balance))
{
document.getElementById('paying_now').value=0;
document.getElementById('paid').value=paid;
document.getElementById('balance').value=balance;
alert("Amount Paying now cannot be higher than balance amount");
return;
}
document.getElementById('paid').value = parseInt(paid)+parseInt(paying_now);
document.getElementById('balance').value = parseInt(balance)-parseInt(paying_now);
}
HTML
<table>
<tr>
<td>
<strong>Netpay:</strong>
<input type='text' id='net_pay' value = '1000' readonly />
</td>
<td>
Paid: <input type='text' value='100' id='paid' name='paid' readonly />
<input type='hidden' value='100' id='paid_hidden' ></td>
</td>
<td>
<strong>Balance:</strong>
<input type='text' value='900' id='balance' readonly />
<input type='hidden' value='900' id='balance_hidden' />
</td>
<td>
<strong>Paying now:</strong><input type='text' id='paying_now' onkeyUp='aa(this.value);' />
</td>
</tr>
</table>
无论如何,这里有一个带有以下代码的 JSFiddle: http://jsfiddle.net/JeSZX/
最佳答案
您的 JScript 代码基本上执行您所描述的您希望它执行的操作(但也许我理解错误)。
每当您的立即付款字段中有一些不是数字的值(即什么都没有或字母)时,就会出现 NaN。为了解决这个问题,您需要在使用变量 paying_now
进行一些算术运算之前检查它的内容,例如与 isNaN()
功能:
if (isNaN(paying_now) == false) {
alert ("Not a number!");
return;
}
您的演示 html 代码稍微混淆了问题,回声和表构造不是您问题的一部分。
尝试稍微简化一下,如下所示:
Netpay:
<input type='text' id='net_pay' value = '1000' readonly />
Paid:
<input type='text' value='100' id='paid' name='paid' readonly />
<input type='hidden' value='100' id='paid_hidden' />
Balance:
<input type='text' value='900' id='balance' readonly />
<input type='hidden' value='900' id='balance_hidden' />
Paying now:
<input type='text' id='paying_now' onkeyUp='aa(this.value);' />
关于文本框之间的 Javascript 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8252853/