0

我没有使用此代码获得所需的输出。一切似乎都正常,除非您输入 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;
            }
        });
    }
});
4

2 回答 2

2

您的值被解释为字符串,而不是数字。看看调试时会发生什么:

调试值

所以比较是字符串比较(“按字母顺序”,“100”在“20”之前)。当您使用运算符时,它也会进行字符串连接+

您需要在使用它们之前将值转换为数字,使用Number(),parseFloat()parseInt(), 取决于。

于 2013-07-25T14:41:24.180 回答
0

当 Jason P 回答时,我正在这样做。你真的使用字符串而不是数字。我曾经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;
            }
        });
    }
});
于 2013-07-25T14:46:00.050 回答