2011-05-06 27 views
1

我試圖創建一個簡單的形式計算,其中在name屬性開始有小計每個輸入字段中的值:通過JavaScript表單元素循環和增加所獲取的價值

<script type="text/javascript" src="jq.js"></script> 

<script type="text/javascript"> 
$(function(){ 

var qty = 0; 
var price = 0; 
var subtotal = 0; 
var qty_r = []; 
var price_r = []; 
var subs_r = []; 
var total = 0; 

$('input[name^=qty]').each(function(index) { 
    qty_r[index] = $(this).val(); 
}); 

$('input[name^=price]').each(function(index){ 
    price_r[index] = $(this).val(); 
}); 

var j = 0; 
for(j = 0; j<=2; j++){ 

    subs_r[j] = parseInt(price_r[j]) * parseInt(qty_r[j]); 

} 




$('input[name^=subtotal]').each(function(index){ 
    $(this).val(subs_r[index]); 
}); 


$('input[name^=qty]').keyup(function(){ 
    var basis = $(this).attr("id"); 
    var numbasis = basis.toString(); 

    qty = $(this).val(); 
    price = $('input[name=' + numbasis + ']').val(); 


    subtotal = parseInt(qty) * parseInt(price); 

    $("#subtotal" + numbasis).val(subtotal); 

這在這裏我有麻煩的部分:

$("input[name=subs]").each(function(index){ 
      total = parseInt($(this).val()) + total; 
      $('#total').val(total); 

     }); 

}); 




}); 
</script> 

而這裏也正是其正在計算的數據來自:

<?php $products = array(array("prodname"=>"mais", "qty"=>5, "price"=>15), array("prodname"=>"strawberry", "qty"=>7, "price"=>25), array("prodname"=>"kambing", "qty"=>14, "price"=>3)); ?> 
    <table border="1"> 
    <tr> 
    <th>Product</th> 
    <th>Qty</th> 
    <th>Price</th> 
    <th>Subtotal</th> 
    </tr> 
    <?php foreach($products as $key=>$prods){ 

    ?> 
    <tr> 
    <td><input type="text" name="prodname<?php echo $key; ?>" value="<?php echo $prods['prodname']; ?>"/></td> 
    <td><input type="text" id="<?php echo $key; ?>" name="qty<?php echo $key; ?>" value="<?php echo $prods['qty']; ?>"/></td> 
    <td><input type="text" name="<?php echo $key; ?>" id="price<?php echo $key; ?>" value="<?php echo $prods['price']; ?>"/></td> 
    <td><input type="text" name="subs" id="subtotal<?php echo $key; ?>" /></td> 
    </tr> 

    <?php } ?> 

    </table> 
Total: <input type="text" id="total"/><br/> 

問題是我總是得到NaN。

+0

我有類似的行爲。嘗試使用'total = parseInt($(this).val())+ parseInt(total);'確保整數值被計數,總和不被視爲字符串值。它必須是這種錯誤,否則就會說一個數字。//編輯:我已經添加它作爲一個可能的答案下面。 – 2011-05-06 23:35:16

回答

1

如果你使用NaN,你可能試圖parseInt返回值爲NaN的東西。你可以做

$("input[name=subs]").each(function(index) { 
    total = (parseInt($(this).val(), 10) || 0) + total; 
    $('#total').val(total); 
}); 

什麼將總是隻增加總數。

+0

爲什麼這是downvoted? – 2011-05-06 23:49:19

+0

你的猜測和我一樣好。 – Robert 2011-05-07 00:32:50

1

讓我們做出一個可能的答案,請嘗試使用:

total = parseInt($(this).val()) + parseInt(total); 

還要確保$(本).VAL()有一個適當的值隨處可見。如果它是空白的,你將得到NaN。對於幾乎任何其他您將得到正確的結果:http://www.w3schools.com/jsref/jsref_parseInt.asp

1

它看起來像您可能會使用錯誤的選擇器來設置您用來做最後計算的小計值。它不應該是這樣的:

$('input[id^=subtotal]').each(function(index){ 
    $(this).val(subs_r[index]); 
});