user3366530
user3366530

Reputation: 9

How to set a total in a column in a table?

I have a basic table with names and prices generated according to buttons in the website. I need to compute the total for this table.

<table id="countit">
 <tr>
   <th >name</th>
   <th >price</th>
 </tr>
 <tr>
   <td  id ="name"></td>       //this is dynamically generated through buttons
   <td id ="price" ></td>      //this is dynamically generated through buttons
 </tr>
 <tr>
   <th >total</th>
   <th id="grandtotal" ></th>   //total goes here
 </tr>
</table>

Can anyone tell me how to do it in Javascript, please?

Upvotes: 0

Views: 130

Answers (2)

shin
shin

Reputation: 1681

Click here for Fiddle

    <table id="countit" border="1">
 <tr>
   <th >name</th>
   <th >price</th>
 </tr>
 <tr>
   <td  id ="name">aaa</td>       
   <td name="price">10</td>      
 </tr>
 <tr>
   <td  id ="name">bbb</td>       
   <td name="price">20</td>      
 </tr>
 <tr>
   <td  id ="name">ccc</td>       
   <td name="price">30</td>      
 </tr>
 <tr>
   <th >total</th>
   <th id="grandtotal" ></th> 
 </tr>
</table>

<script>

    var tds = document.getElementsByName("price");

    var total = 0;

    for(var i=0; i<tds.length; i++)
    total += parseInt(tds[i].innerHTML);

    document.getElementById('grandtotal').innerHTML=total;

</script>

Upvotes: 2

sumitb.mdi
sumitb.mdi

Reputation: 990

 <tr>
  <td  id ="name"></td>       
  <td name ="price" ></td>      
 </tr>

If you are generating table rows from any back-end language then provide a common value to "name" attribute. Then from the javascript get these element using

var prices=getElementsByName('price'); 
for(i=0;i<prices.length;i++){
   total = total+parseInt(prices[i].innerHTML);
}

once you get the total you can set this value to any element.

document.getElementById('grandTotal').innerHTML = total; 

Upvotes: 0

Related Questions