SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2007
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Calculator working out percentages

    Hello

    If you go to this page https://www.barnardos.org.uk/donate/...ingle+Donation
    and enter a donation amount and then click on the yes box you will see the percentage of the gift aid is worked out.

    Can anyone help with a JS way to do this please?

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,055
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    This should get you started:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Percentage calculator</title>
      </head>
      
      <body>
        <div>
          <label for="amount">Amount </label>
          <input id="amount" type="text" />
          <span id="total"></span>
        </div>
        <div>
          <label for="addPercentage">Add percentage</label>
          <input type="checkbox" id="addPercentage">
        </div>
        
        <script>
          var percentage = document.getElementById("addPercentage"),
              amount = document.getElementById("amount"),
              total = document.getElementById("total");
              
          percentage.onchange = function(){
            if(this.checked){
              if (amount.value && amount.value.match(/^(\d|,)*\.?\d*$/)){
                total.innerHTML = "Value plus 25% is " + (Number(amount.value) * 1.25).toFixed(2);
              }
            } else {
              total.innerHTML = "";
            }
          }
        </script>
      </body>
    </html>
    When you check the checkbox, presuming that there is a value entered in the amount field, the script tests the amount against a reg ex to verify that it is a valid number (matches numeric with commas and a single decimal point), then calculates the percentage accordingly.

    It is by no means perfect, but should get you thinking in the right direction.
    If you have any questions, just let me know.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •