Search code examples
javascriptphpjqueryshopping-cartinvoice

computing total price of shopping cart invoice


In my code after users choose products and go to cart page, my cart page creates an html structure like this for all total prices of selected products: below here x indicates a number which is id of good that I fetch from Session, so every time these differ, also the number of fields changes every time based on user's choice

<span class="total-x"> some value</span>
<span class="total-x"> some value</span>
<span class="total-x"> some value</span>
.
.
.
.
<span class="total-x"> some value</span>

for example if cart gets id=3 form session after some other codes, page creates a field like this:

 <span class="total-3"> some value [has been computed]</span>

I want to sum up value of those field and put in a field like this:

<span id=total-all> </span> 

I ask for every which would lead me to over come this.


Solution

  • Try to use start with selector to identify that unknown class,

    $("#total-all").text($("span[class^='total-']").get().reduce(function(a,b){
      return a + (+$(b).text());
    },0));
    

    DEMO