Jump to content

Looping Through List Items for Sum?


barkster

Recommended Posts

I have an invocing system that I'm playing with and right now I have several rows of invoice details that have line items with quantity and amounts.  I use ajax to update each row onchange but I have yet figured out a way to update my grand total when that happens.  How can I loop through the list items onchange to get my new total?  Here is an example of the items

 

<div id="rows">
   <ul id="1">
      <li class="col1">Description1</li>
      <li class="col2">1</li>
      <li class="col3">2.50</li>
    </ul>
   <ul id="2">
      <li class="col1">Description2</li>
      <li class="col2">3</li>
      <li class="col3">23.25</li>
   </ul>
</div>

Link to comment
https://forums.phpfreaks.com/topic/174700-looping-through-list-items-for-sum/
Share on other sites

sorry can't edit but I'm trying to get value of textbox inside the li tag

 

<div id="rows">
   <ul id="1">
      <li class="col1">Description1</li>
      <li class="col2"><input name="qty" type="text" value="1" /></li>
      <li class="col3"><input name="amount" type="text" value="2.5" /></li>
    </ul>
   <ul id="2">
      <li class="col1">Description2</li>
      <li class="col2"><input name="qty" type="text" value="1" /></li>
      <li class="col3"><input name="amount" type="text" value="30" /></li>
   </ul>
</div>

I think I figured it out but don't know if it is best way

 

function updatetotal() {
var div = document.getElementById('rows');
var obj=div.getElementsByTagName('ul');
var newtotal = 0;
for (var i=0; i<obj.length; i++) {
	console.log(obj[i].getElementsByTagName('LI')[1].firstChild.value);
	console.log(obj[i].getElementsByTagName('LI')[2].firstChild.value);
	//console.log(obj[i].getElementsByTagName('LI')[1].firstChild.nodeValue);//use if you want innerhtml of li tag
	newtotal = newtotal + (obj[i].getElementsByTagName('LI')[1].firstChild.value * obj[i].getElementsByTagName('LI')[2].firstChild.value)
}
console.log("The Grand total is %s",newtotal);
document.getElementById('total').innerHTML = formatCurrency(newtotal);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.