How to do Total Sum from JS in Django

let x = document.getElementById("food_price");

console.log(x);

enter image description here enter image description here

I try to get total of food items from JS, but I could not find the solution, can anyone help me.

Your HTML

is invalid, because an id needs to be unique in the whole document. Yet, your id of food_price repeats on each and every row.

A solution which would work now

This is how you could do it now:

let sum = 0;
let prices = document.querySelectorAll('[id=food_price]');
for (let i = 0; i < prices.length; i++) {
    sum += parseInt(prices[i].innerText.substring(2).trim());
}

!!! But this would still leave your HTML invalid !!!

How to improve your HTML

Change your Django template, so, instead of

<td class="text-right" id="food_price">

you will have

<td class="text-right food_price">

essencially the td will have the text-right and the food_price class at the same time. And then change the solution to

let sum = 0;
let prices = document.querySelectorAll('.food_price');
for (let i = 0; i < prices.length; i++) {
    sum += parseInt(prices[i].innerText.substring(2).trim());
}

Note that in the JS we only change the selector. Please fix your HTML so it will be valid. Remember: ids are meant to be unique in the whole document. If something is not unique in the document, use class instead.

let sum = 0;
let prices = document.querySelectorAll('.food_price');
for (let i = 0; i < prices.length; i++) {
    sum += parseInt(prices[i].innerText.trim().substring(3).trim());
}
console.log(sum);
<table>
    <tr>
        <td class="text-right food_price"> 
            RS. 2
        </td>
    </tr>
    <tr>
        <td class="text-right food_price"> 
            RS. 3
        </td>
    </tr>
    <tr>
        <td class="text-right food_price"> 
            RS. 5
        </td>
    </tr>
    <tr>
        <td class="text-right food_price"> 
            RS. 7
        </td>
    </tr>
</table>

Back to Top