2011-09-26 17 views
1

此代碼位於jquery移動窗體中。它將數字相加並在禁用的文本框中顯示總數。當總數爲100時,繼續(提交)按鈕啓用。
偶爾不會在JQuery中正確添加數字

當沒有值時,會話var代碼正確放入零。

問題: 有時候人們會在零之後鍵入一個數字(例如:0100)。
看起來像這樣,加上刪除一個數字會導致號碼不能正確合併。

我可以用你的幫助:
入門的總計算擺脫Bug多多隨機的,特別是當值清零。我應該使用parseInt嗎?

在此先感謝。

<script> 
$(document).ready(function() { 
<?php 
if (!isset($_SESSION['num1'])) { 
    echo "$('#num1').val(0);"; 
} 
if (!isset($_SESSION['num2'])) { 
    echo "$('#num2').val(0);"; 
} 
if (!isset($_SESSION['num3'])) { 
    echo "$('#num3').val(0);"; 
} 
if (!isset($_SESSION['num4'])) { 
    echo "$('#num4').val(0);"; 
} 
?> 

//to handle previously entered values if back button used: <br/> 

var tot = ($('#num1').val() - 0) + 
    ($('#num2').val() - 0) + 
    ($('#num3').val() -0) + 
    ($('#num4').val() - 0); 
    $('#total').val(tot); 
    if (tot==100) { 
     $('#continue').removeAttr('disabled');    
    } else { 
     $('#continue').attr("disabled","disabled");    
    } 

    //to handle numbers on update. 
    $('input[name^="int"]').keypress(function() { 
     var tot = ($('#num1').val() - 0) + 
      ($('#num2').val() - 0) + 
      ($('#num3').val() -0) + 
      ($('#num4').val() - 0); 
      $('#total').val(tot); 
      if (tot==100) { 
       $('#continue').removeAttr("disabled"); 
      } else { 
       $('#continue').attr("disabled","disabled"); 
      } 

     }); 

回答

1

parseInt($('#num').val(),10)代替$('#num').val() - 0嘗試將字符串轉換爲數字

-1

要使用的代碼只有一行得到一個int的列輸入的:

var n=parseInt($('#num').val(),10)||0; 
+0

此評價將從字符串中提取所有數字(以及小數點和減號),然後嘗試將它們轉換爲數字。如果給出像「5.36.31」這樣的字符串(或者如果用戶的本地區域使用逗號而不是句點來表示小數),這仍然會失敗。 – Blazemonger

+0

@ mblase75爲true,修改爲解決這些問題。 – Shad

+0

你爲什麼這麼努力地重新發明輪子?這正是'parseInt'和'parseFloat'的作用。 – Blazemonger

0

您應該使用parseInt代替。但是,請確保您正確使用它:

parseInt("09",10); // equals 9 
parseInt("09); // equals zero, because it thinks it's an octal number 
相關問題