Open Source VAT Calculator Implementation in HTML, JavaScript, and Bootstrap

7 Min Read

I was recently tasked with building a custom website using HTML, CSS, JavaScript, and Bootstrap. One of the key requirements was implementing a VAT (Value Added Tax) calculator that would allow users to perform quick tax calculations. The calculator needed to be dynamic, user-friendly, and flexible enough to handle different currencies and calculation types.

Complete Open Source Code

<div id="vat-calculator"></div>

<script>
  class VATCalculator {
    constructor() {
      this.amount = 0;
      this.vatRate = 20;
      this.calculationType = "Add VAT";
      this.currency = "GBP";
      this.rounding = "nearest";
      this.vatAmount = 0;
      this.totalAmount = 0;

      this.handleCalculation = this.handleCalculation.bind(this);
      this.handleChange = this.handleChange.bind(this);
    }

    handleCalculation() {
      let vat = 0;
      let total = 0;

      if (this.calculationType === "Add VAT") {
        vat = this.amount * (this.vatRate / 100);
        total = this.amount + vat;
      } else if (this.calculationType === "Remove VAT") {
        vat = this.amount - this.amount / (1 + this.vatRate / 100);
        total = this.amount - vat;
      }

      // Handle rounding
      if (this.rounding === "nearest") {
        vat = Math.round(vat * 100) / 100;
        total = Math.round(total * 100) / 100;
      }

      this.vatAmount = vat;
      this.totalAmount = total;
      this.render();
    }

    handleChange(event) {
      switch (event.target.id) {
        case "amount":
          this.amount = parseFloat(event.target.value);
          break;
        case "vat-rate":
          this.vatRate = parseFloat(event.target.value);
          break;
        case "calculation-type":
          this.calculationType = event.target.value;
          break;
        case "currency":
          this.currency = event.target.value;
          break;
        case "rounding":
          this.rounding = event.target.value;
          break;
      }
      this.render();
    }

    render() {
      const calculatorDiv = document.getElementById("vat-calculator");
      calculatorDiv.innerHTML = `
        <h2 style="color: #bf7f00">VAT Calculator</h2>
        <p>The VAT Calculator is a quick and easy tool for calculating VAT on goods and services. It helps businesses and individuals add or remove VAT from any amount, ensuring accuracy when invoicing or budgeting. Whether you’re a business calculating VAT to pay or a customer checking VAT on a purchase, this tool simplifies your tax calculations.</p>
        <div class="form-group" style="margin-bottom: 15px">
          <label for="amount">Amount (${this.currency}):</label>
          <input type="number" id="amount" value="${this.amount}" onchange="calculator.handleChange(event)" placeholder="Enter amount" style="width: 100%; padding: 10px; font-size: 16px; border-radius: 5px; border: 1px solid #ccc" />
        </div>
        <div class="form-group" style="margin-bottom: 15px">
          <label for="vat-rate">VAT Rate (%):</label>
          <input type="number" id="vat-rate" value="${this.vatRate}" onchange="calculator.handleChange(event)" placeholder="Enter VAT rate" style="width: 100%; padding: 10px; font-size: 16px; border-radius: 5px; border: 1px solid #ccc" />
        </div>
        <div class="form-group" style="margin-bottom: 15px">
          <label for="calculation-type">Calculation Type:</label>
          <select id="calculation-type" value="${this.calculationType}" onchange="calculator.handleChange(event)" style="width: 100%; padding: 10px; font-size: 16px; border-radius: 5px; border: 1px solid #ccc">
            <option value="Add VAT">Add VAT</option>
            <option value="Remove VAT">Remove VAT</option>
          </select>
        </div>
        <div class="form-group" style="margin-bottom: 15px">
          <label for="currency">Currency:</label>
          <select id="currency" value="${this.currency}" onchange="calculator.handleChange(event)" style="width: 100%; padding: 10px; font-size: 16px; border-radius: 5px; border: 1px solid #ccc">
            <option value="GBP">GBP</option>
            <option value="EUR">EUR</option>
            <option value="USD">USD</option>
          </select>
        </div>
        <div class="form-group" style="margin-bottom: 15px">
          <label for="rounding">Rounding Preference:</label>
          <select id="rounding" value="${this.rounding}" onchange="calculator.handleChange(event)" style="width: 100%; padding: 10px; font-size: 16px; border-radius: 5px; border: 1px solid #ccc">
            <option value="nearest">Round to the nearest penny</option>
            <option value="decimal">Keep decimals</option>
          </select>
        </div>
        <button onclick="calculator.handleCalculation()" style="width: 100%; padding: 10px; background-color: #343a40; color: #ffffff; font-size: 16px; border-radius: 5px; cursor: pointer">Calculate VAT</button>
        <div class="results" style="margin-top: 20px; padding: 15px; background-color: #e9ecef; border-radius: 5px">
          <p><strong>VAT Amount:</strong> ${this.currency} ${this.vatAmount.toFixed(2)}</p>
          <p><strong>Total Amount:</strong> ${this.currency} ${this.totalAmount.toFixed(2)}</p>
        </div>
      `;
    }
  }

  const calculator = new VATCalculator();
  calculator.render();
</script>

Primary programming language is JavaScript. Specifically, it’s written in modern JavaScript using ES6+ features

Breaking Down the Code

Let’s walk through the main components and how they work:

The Class Structure

The calculator is built using a class-based approach, which makes the code organized and maintainable. The VATCalculator class handles all the functionality, from calculations to rendering the UI.

Key Components Explained

  1. Constructor Setup
    • The constructor initializes default values for amount, VAT rate, calculation type, currency, and rounding preferences
    • It also binds the event handlers to maintain proper context
  2. VAT Calculation Logic The handleCalculation method contains two main calculation paths:
    • Adding VAT: Calculates VAT as a percentage of the base amount
    • Removing VAT: Extracts VAT from a total amount using the formula: amount – (amount / (1 + vatRate/100))
  3. Event Handling The calculator uses event handlers to:
    • Update values when input fields change
    • Trigger recalculations
    • Handle different input types (numbers, dropdowns)
  4. Dynamic Rendering The render method:
    • Creates a responsive form interface
    • Updates results in real-time
    • Maintains state across re-renders
    • Applies consistent styling using inline CSS

Implementation Best Practices

Throughout the code, you’ll notice several good practices:

  1. Separation of Concerns
    • Calculation logic is separate from rendering logic
    • Event handling is cleanly separated into its own method
  2. Error Prevention
    • Number parsing to ensure proper calculations
    • Rounding options to handle decimal precision
    • Input validation through HTML5 number fields
  3. User Experience
    • Clear labeling and organization of inputs
    • Immediate feedback on changes
    • Professional styling with Bootstrap-inspired design

Making It Your Own

This code is designed to be easily customizable. You can:

  • Modify the VAT rates for different regions
  • Add more currency options
  • Implement additional rounding methods
  • Customize the styling to match your website
  • Add validation rules or error handling

Final Thoughts

Whether you’re building an e-commerce platform, accounting tool, or just need a reliable VAT calculator, this code provides a solid foundation. It’s written to be both functional and educational, helping other developers understand how to implement similar features in their projects.

Remember to test thoroughly when implementing tax-related calculations in production environments, as accuracy is crucial for business applications.

Feel free to use this code in your projects, and don’t hesitate to reach out if you have questions or suggestions for improvements!

Share This Article
Learning SEO since 2018. SEO Specialist Who Claims To Have Ranked 50+ Sites On 1st Page. I enjoy doing low difficulty keyword research, yes I have the skill to spy competitor keywords and grab ranking opportunities from them.
Leave a Comment