我没有使用此代码获得所需的输出。一切似乎都在起作用,除非你输入100到199之间的任何东西。它在另一个框中给出一个负数,当我希望它只是将余额分成两个框。你可以在这里看到一个有效的例子:http://jsfiddle.net/bFJq2/(输入100看看我的意思)
不确定是否存在我做错的事情,我觉得它将数字视为小数或其他东西。非常感谢任何帮助。
这是JS:
// make sure both inputs are equal to balance
$('input[id*="amount"]').on("blur", function() {
var balance = $('#balance').val()
,thisAmount = $(this)
,otherAmount = $('input[id*="amount"]').not(this);
// check if value is less than balance
if(thisAmount.val() < balance && thisAmount.val() + otherAmount.val() <= balance){
// if so populate other input with remaining amount
otherAmount.val(balance - thisAmount.val());
}
// check to make sure amount is not greater than balance
if((thisAmount.val() + otherAmount.val()) > balance){
$('input[id*="amount"]').not(this).val(function(){
// if value is greater than balance, just split balance into both amounts
if(thisAmount.val() > balance){
thisAmount.val(balance/2);
return balance/2;
}
});
}
});
答案 0 :(得分:2)
您的值被解释为字符串,而不是数字。看看调试时会发生什么:
因此,比较是字符串比较(“按字母顺序”,“100”在“20”之前)。当您使用+
运算符时,它也会进行字符串连接。
您需要在使用Number()
,parseFloat()
或parseInt()
之前将值转换为数字。
答案 1 :(得分:0)
parseInt()
来纠正。
// make sure both inputs are equal to balance
$('input[id*="amount"]').on("blur", function() {
var balance = parseInt($('#balance').val());
var thisAmount = $(this);
var otherAmount = $('input[id*="amount"]').not(this);
// check if value is less than balance
if(parseInt(thisAmount.val()) < balance && parseInt(thisAmount.val()) + parseInt(otherAmount.val()) <= balance){
// if so populate other input with remaining amount
otherAmount.val(balance - thisAmount.val());
}
// check to make sure amount is not greater than balance
if((parseInt(thisAmount.val()) + parseInt(otherAmount.val())) > balance){
$('input[id*="amount"]').not(this).val(function(){
// if value is greater than balance, just split balance into both amounts
if(parseInt(thisAmount.val()) > balance){
thisAmount.val(balance/2);
return balance/2;
}
});
}
});