使用jQuery计算2个数量时不受欢迎的效果

时间:2013-07-25 14:28:30

标签: jquery numbers calculated-field jquery-calculation

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

2 个答案:

答案 0 :(得分:2)

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

Debug values

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

您需要在使用Number()parseFloat()parseInt()之前将值转换为数字。

答案 1 :(得分:0)

当杰森P回答时,我正在这样做。你真的使用字符串而不是数字。我用parseInt()来纠正。

Edited working fiddle

// 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;
            }
        });
    }
});