Jacky
Jacky

Reputation: 781

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.

enter image description here

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 isenter image description here

Upvotes: 0

Views: 1061

Answers (2)

Szymon
Szymon

Reputation: 91

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.

Upvotes: 1

TKoL
TKoL

Reputation: 13892

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

Upvotes: 4

Related Questions