views:

438

answers:

1

Hi , I want to implement a VAT switcher as you can see on http://aria.co.uk top right corner although I want to do it on the client side only.

Below is something I came up with, although I need to:

  • switch VAT back and forth (my example goes just one way)
  • save and read the toggled state from a cookie for persistency
  • have it unobtrusive / display the switch link only if JS is available

    <html>

    <head>

    <title>VAT Switch</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"&gt;&lt;/script&gt;

    <script type="text/javascript">

    function VATswitch(){

    var price = $(".price strong span").text();

    price = price * 10 / 12;

    $(".price strong span").text(price);

    var excl_incl = $(".price em").text();

    excl_incl = "(excl. VAT)";

    $(".price em").text(excl_incl);

    } </script>

    </head>

    <body>

    <a href="#" onclick="VATswitch();" id="vat_switch">Switch VAT</a>

    <p class="price">

    <strong>£<span>120</span></strong>

    <em>(incl. VAT)</em>

    </p>

    </body>

    </html>

Please help.

+3  A: 

The easiest way would be to render both prices to your page and then control the visibility with jquery/css, something like:

<div class="price">
    <span class="incVAT">£11.50 (incl VAT)</span>
    <span class="exVAT">£10.00 (ex VAT)</span>
</div>

Then your toggler can do:

$('.price .incVAT').show();
$('.price .exVAT').hide();

and vice versa

Edit: I wouldn't do the calculations client side. Presumably you're making a shop of some kind, well not all your products will have VAT, and some may have different rates.

Edit re comment:

There is a jquery cookie library that will help you do the cookies, so all you need to do to persist it is read the value on load:

$(function(){

    ShowPrices();

    $('a#vattoggle').click(function(){
        if($.cookie('VATMODE') == "INC"){
            $.cookie('VATMODE', 'EX');
        } else {
             $.cookie('VATMODE', 'INC')
        }
        ShowPrices();
        return false
    });
});


function ShowPrices(){
    if($.cookie('VATMODE') == "INC"){
        $('.price .incVAT').show();
        $('.price .exVAT').hide();
    } else {
        $('.price .incVAT').hide();
        $('.price .exVAT').show();
    }
}
Andrew Bullock
All of them do have VAT the same VAT. What is the best way to make it actually toggle and how do I make it persistent.