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 に答える