0

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

3
  • 3
    Well of course it is. $(".total").val(tot); modifies EVERY element of class total. Try $(".total").eq(i).val(tot); Commented Nov 22, 2019 at 11:00
  • @KhalilKhalil i have already tired it won't work Commented Nov 22, 2019 at 11:03
  • @KhalilKhalil $(".total")[i].val(tot) wont work as $(".total")[i] is getting the underlying DOM object therefore it doesnt have a val() method that is a jquery method Commented Nov 22, 2019 at 11:13

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

i have another doubt can you help me
how to sum the value of total
before your loop, do var total = 0; inside your loop, do total += tot; After your loop, total will be all tot added up
it is not adding
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.