tags:

views:

56

answers:

2

Hi guys,

I have a php script which generates a pricelist in a table. Example of a generated table:

<table>
  <thead>
    <tr>
    <th></th>
    <th>100</th>     
    <th>+100</th>           
    </tr>
  </thead>
  <tbody>
    <tr>
           <th>A5<span>210x148</span></th>
           <td>€65.00</td>
           <td>€8</td>
        </tr>
        <tr>
           <th>A4<span>297x210</span></th>
           <td>€75.00</td>
           <td>€16</td>
        </tr>       
  </tbody>
</table>

Basically what I want to do is make a button to add VAT. So: take the values from the price cells, add 21% and replace the original value. If the button is clicked again, it restarts.

My issue is that I am not familiar with jquery and can not figure out how to extract and rewrite the values per cel. I can get the effect I want if I add an id to a cell, however I can't seem to figure out how to do it for all the cells. Another thing I can't get working is stripping away the currency sign to do the calculation.

Any help would be greatly appreciated.

+1  A: 

One approach would be to give those 'price' cells a class name

<td class='price'>

and then loop through that collection of elements:

$('price').each(function(index) {
     vat = $(this).text().replace("$", "") * 1.21;
     $(this).text() = vat;
  });

Untested but hopefully it communicates the idea.

LesterDove
`<td 'class=price'>` huh? Did you mean `<td class='price'>`
Jamie Wong
oops; corrected.
LesterDove
Fixed the class name :-), you could use `parseFloat` instead, this would mean you won't have to guess what currency / format they have it in.
ILMV
i just read more carefully and realized that we're not trying to sum them (i should never SO before my first coffee.)
LesterDove
@ILMV: *parseFloat()* isn't a locale dependent function, it looks for the floating point grammar at the start of a string. This means you might need to check for a comma as the decimal separator. I tend to find *Number()* or unary *+* more useful than *parseFloat()* for all sorts of reasons.
Andy E
@andy Ah I see, thanks for the info :-)
ILMV
+1  A: 

You can add a class to EVERY table cell where you'll have the price to compute VAT like

<td class='priceCell'>

and then do something like on the first press button

$('priceCell').each(function(index) {
     $(this).text() = calculateVAT($(this).text());
  });

Where calculateVAT is a function javascript who calculates VAT. As this solution performs float point calculation on a number that could be rounded, another possible elegant solution is to add an hidden column with VAT-added totals and the button just switch between the two columns

Mauro
I like the hidden column solution, since it allows me to do most of the programming in PHP. Let me try that...
Maikelv
A hidden column is actually a very good idea, saves calculating it all client side :-)
ILMV