我想通过JavaScript添加单列值

当用户输入数量时,数量乘以价格列,并显示在“您的账单”列中。问题是,当用户单击“订购”按钮时,“您的账单”列中的所有值都会添加并显示在屏幕上。

请告诉我如何对“您的帐单列”中的所有值求和

javascript - 通过javascript的列值总和-LMLPHP

我的查看文件是

    <tbody>

<?php $i=0; foreach($result as $row){
?>
     <tr>
         <th class="item-lists">
             <?php echo $row->recipe_name;?>
         </th>
         <th class="pre-top">
            <?php echo $row->quantity;?>
         </th>
        <th class="pr-right">
            <span id="priceT<?php echo $i;?>" ><?php echo $row->price;?></span>
        </th>
        <th class="pr-right">

            <input type="text" class="container" value="" onfocus="this.value = '';" onblur=";}" style="width: 60px" id="quantityT<?php echo $i;?>" onkeyup="CalculatePrice (<?php echo $i;?>)">
        </th>

         <th class="clearfix">
             <input type="text" class="container" value="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}" style="width: 60px"id="TPrice<?php echo $i;?>">
         </th>
     </tr>
<?php
$i++;
} ?>
     </tbody>


和javascript代码

 function CalculatePrice (id) {


        var startP = parseInt (document.getElementById ("priceT"+id).innerHTML);
        var startQ = parseInt (document.getElementById ("quantityT"+id).value);

        var Bill = 0;
        if (!isNaN ( startP)&&!isNaN(startQ))
        {var Bill = startP * startQ}


        document.getElementById ("TPrice"+id).value =  Bill;



    }

最佳答案

我认为这可能有效:

首先为<th class="clearfix">设置一个新类,例如... <th class="clearfix product-price">,并在输入中添加价格data-price(出于安全原因,用户可以更改输入文本的值)。

然后用javascript:

var order = document.getElementById('order');
var totalPrice = 0;

order.addEventListener('click', function(){
    var productsPrice = document.getElementsByClassName('product-price');
    console.log(productsPrice);
    for(var i = 0; i < productsPrice.length; i++){
        totalPrice += parseInt(productsPrice[i].dataset.price);
    }
    alert("Total = "+totalPrice);
});


我做了一个fiddle

就我个人而言,出于我之前解释的原因,我使用span而不是文本input

关于javascript - 通过javascript的列值总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31855317/

10-12 00:02
查看更多