循环遍历javascript中的表单元素并添加获取的值

时间:2011-05-06 23:29:26

标签: php javascript jquery

我正在尝试创建一个简单的表单来计算每个输入字段中的值,这些字段在name属性的开头有小计:

<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作为结果。

3 个答案:

答案 0 :(得分:1)

如果您正在获取NaN,您可能正在尝试解析返回值为NaN的东西。你可以做到

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

总是只会添加总数。

答案 1 :(得分:1)

让我们做出一个可能的答案,尝试使用:

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

还要确保$(this).val()在任何地方都有适当的值。如果它是空白的,那么你将得到NaN。对于几乎任何其他人,您将获得正确的结果:http://www.w3schools.com/jsref/jsref_parseInt.asp

答案 2 :(得分:1)

看起来您可能正在使用错误的选择器来设置您用于进行最终计算的小计值。不应该这样:

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