DEV Community

Anatoly
Anatoly

Posted on

Simple VAT Calculator On JS

This simple VAT calculator allows users to enter the amount and the VAT rate. In one click, the VAT amount and total amount appear on the screen.

Image description

HTML CODE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>VAT Calculator</title>
</head>
<body>

<div class="calculator">
    <h2>VAT Calculator</h2>
    <label for="amount">Amount (excluding VAT):</label>
    <input type="number" id="amount" placeholder="Enter amount" required>

    <label for="vatRate">VAT Rate (%):</label>
    <input type="number" id="vatRate" placeholder="Enter VAT rate" required>

    <button onclick="calculateVAT()">Calculate VAT</button>

    <div class="result">
        <p>VAT Amount: <span id="vatAmount">0</span></p>
        <p>Total Amount (including VAT): <span id="totalAmount">0</span></p>
    </div>
</div>

<script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

*CSS Code:
*

body {
    font-family: 'Arial', sans-serif;
    background-color: #f4f4f4;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.calculator {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    text-align: center;
}

label {
    display: block;
    margin-top: 10px;
}

input {
    width: 100%;
    padding: 8px;
    margin-top: 5px;
}

button {
    background-color: #4caf50;
    color: #fff;
    padding: 10px;
    margin-top: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.result {
    margin-top: 20px;
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

*JS Code:
*

function calculateVAT() {
    const amount = parseFloat(document.getElementById('amount').value);
    const vatRate = parseFloat(document.getElementById('vatRate').value);

    if (isNaN(amount) || isNaN(vatRate)) {
        alert('Please enter valid numbers for amount and VAT rate.');
        return;
    }

    const vatAmount = (amount * vatRate) / 100;
    const totalAmount = amount + vatAmount;

    document.getElementById('vatAmount').innerText = vatAmount.toFixed(2);
    document.getElementById('totalAmount').innerText = totalAmount.toFixed(2);
}
Enter fullscreen mode Exit fullscreen mode

If you have any questions or suggestions, please comment on this post.

Top comments (0)