...

View Full Version : jQuery performing calculations on table cells



maikelv
08-16-2010, 03:11 PM
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.

Spudhead
08-16-2010, 04:41 PM
You know what: I thought this'd be easy. And it's not. Well, I can't make it work, anyhow. I can't make it display a two-decimal-place number when you add the VAT that returns to the original number when you take it off again. I always end up with a different number. Mind, I always was hopeless at maths.

There is another way. It's sort of cheating.

Do your VAT calculation in PHP and get it to churn out the following HTML:


<button id="btnToggleVAT">Show price including VAT</button>

<table>
<thead>
<tr>
<th></th>
<th>100</th>
<th>+100</th>
</tr>
</thead>
<tbody>
<tr>
<th>A5<span>210x148</span></th>
<td><span class="price_net">&euro;65.00</span><span class="price_vat">&euro;70ish</span></td>
<td><span class="price_net">&euro;10</span><span class="price_vat">&euro;12.10</span></td>
</tr>
</tbody>
</table>

Then you can just show/hide the relevant spans:


<script type="text/javascript">

$(function(){

$('.price_vat').hide();

$('#btnToggleVAT').click(function(){

if ( $(this).text() == 'Show price including VAT' ){
$('.price_vat').show();
$('.price_net').hide();
$(this).text('Show price excluding VAT');
}else{
$('.price_net').show();
$('.price_vat').hide();
$(this).text('Show price including VAT');
}
});

});

</script>

:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum