简体   繁体   中英

How to calculate in html table rows using javascript

This is my table image that i have fetched from the another table in this table i am doing some calculation using javascript.When i tried to change the qty value,it should multiply with rate and show it in the total. My problem when i change the value the both rows of the total shows same result.

在此处输入图像描述

My code:

<script type="text/javascript">
    function calculate(id){ 
    var tot = 0;
    var qty = document.getElementsByClassName("qty");
    var rate = document.getElementsByClassName("rate");
    var total = document.getElementsByClassName("total");
for(var i = 0; i < qty.length; i++)
{
        tot = parseFloat(qty[i].value) * parseFloat(rate[i].value);
        $(".total").val(tot);
}

} 
</script>

My result i got is在此处输入图像描述

Well of course it is. $(".total").val(tot); modifies EVERY element of class total. Try $(".total").eq(i).val(tot);

Note: this solution won't work if you have other .total elements on the page, outside of the table you're working on. You'll have to select the table first, $('table#tableid.total').eq(i)... to overcome that issue

It does it cause you did not specify which which row specifically should be updated with the following line of code:

$(".total").val(tot);

What you do instead is updating values of all the fields within the class total.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM