2012-11-26 107 views
1

我有一個發票表單和一個jquery函數。 在發票中,如果我輸入的數量大於可用數量,那麼我必須提醒用戶。jquery事件不能正常工作

我的問題是:讓最大數量是5,如果我輸入數據爲7(單個數字>最大可用數量),那麼我的代碼工作正常。但是,如果我輸入兩個digigist號碼,例如。 17(兩個digists>最大可用數量),那麼我的警報框不會來。 我的意思是onkeyup我的功能只能使用單個數字。

我該如何讓它發生?請幫忙。

 $('input[name="quantity"]').keyup(function() 
     { 
    //problem is here 
     var $tr = $(this).closest("tr"); 
     var unitprice = $tr.find('input[name^="unitprice"]').val(); 

     var q = $tr.find('input[name^="quantity"]').val(); 
     var cq = $tr.find('input[name^="checkquantity"]').val(); 

     if(q>cq) 
     { 
     alert("Error: Quantity value exceeds then available quantity..Max Quantity is "+cq); 
      //this works fine only if single digit is entered in textbox quantity 
     } 

     //----below are some other stuffs -these are working fine 
     $tr.find('input[name^="sprice"]').val($(this).val() * unitprice); 
     var totalPrice = 0; 
     $('input[name="sprice"]').each(function() 
     { 
      totalPrice += parseFloat(this.value); 
      $('[name=subtotal]').val(totalPrice); 
     }); 
    }); 
    -------------- 
    ------------ 
    // Form containing the above textboxes 
     <input type="submit" id="submitbtnId" value="Save"/>` 

回答

1

q > cq在比較兩個字符串,這是不是你想要的。您正試圖比較這些字符串的數值。

使用這個代替:

if (+q > +cq) 
{ 
    // alert your error 
} 

注意的前綴來+標誌的變量,你將它們轉換爲數字。


更重要的是,一旦你得到的值,並將它們轉換爲數字:

var $tr = $(this).closest("tr"); 
var unitprice = +$tr.find('input[name^="unitprice"]').val(); 

var q = +$tr.find('input[name^="quantity"]').val(); 
var cq = +$tr.find('input[name^="checkquantity"]').val(); 

if (q > cq) 
{ 
    alert("Error: Quantity value exceeds then available quantity..Max Quantity is " + cq); 
} 
+0

非常感謝。 –

0

您需要使用parseInt(),以確保你在比較的整數,而不是字符串:

if (parseInt(q, 10) > parseInt(cq, 10)) { 
    /* Rest of your code */ 
} 
0

您的值進行比較,如字符串。如果要比較的數字,無論是使用:

parseInt()parseFloat()

[..].val() * 1,但是這將返回 '男',如果它沒有數字,而parseInt函數()和parseFloat()將返回0