2013-07-25 2 views
0

이 코드로 원하는 결과를 얻지 못했습니다. 예를 들어 100 - 199 사이에 아무 것도 입력하지 않으면 모든 것이 작동하는 것처럼 보입니다. 나머지 상자에 음수가 표시됩니다. 두 상자로 균형을 분할하고 싶을 때입니다. 여기에 실제 예제를 볼 수 있습니다 : http://jsfiddle.net/bFJq2/ (내 말은 100을 입력하십시오)jQuery로 2 개의 금액을 계산할 때 원치 않는 결과가 발생했습니다.

제가 잘못하고있는 것이 있는지 확실하지 않은 경우, 숫자가 소수로 취급되는 것 같습니다. 어떤 도움이라도 대단히 감사합니다. 여기

은 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

귀하의 값은 문자열이 아닌 숫자로 해석되고있다. 당신이 디버깅 할 때 어떻게되는지 :

Debug values

은 그래서 비교가 문자열 비교입니다 ("알파벳", "100"을 "20"전입니다). 또한 + 연산자를 사용할 때 문자열 연결을 수행합니다.

Number(), parseFloat() 또는 parseInt()을 사용하여 값을 사용하기 전에 값을 숫자로 변환해야합니다.

+0

또는'에서는 parseInt()'숫자가 항상있는 경우 정수

Edited working fiddle

. – jalynn2

+0

@ jalynn2 돈이 아니기 때문에 소수점 자리는 괜찮다고 가정했지만, 완성을 위해'parseInt()'를 추가했습니다. –

+0

감사합니다. 나는 그것을 도움이되는 몇 가지 읽기를 다음과 같이 수행했다. http://bit.ly/145x0wg Number()를 사용하여 문자열을 숫자 값으로 변환했다. 다시 한 번 감사드립니다! – souporserious

0

제이슨 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; 
      } 
     }); 
    } 
});