Logo

dev-resources.site

for different kinds of informations.

Easy Discount Calculation: Tax, Fees & Discount Percentage Explained

Published at
1/15/2025
Categories
webdev
javascript
programming
beginners
Author
learninggs
Author
10 person written this
learninggs
open
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained

Discount Calculator💻

we'll explore an Discount Calculator built using HTML, CSS, and JavaScript. I'll break down the entire code step-by-step and explain how each section works. Additionally, I'll provide instructions on how you can test this calculator yourself and suggest improvements you can make to the code.

Test the Code Here 🔗

Test the Code

What This Calculator Does 🧮

This calculator is designed to help users calculate the final price of an item after applying a discount, tax, and any additional fees. It takes inputs for the original price, quantity, discount percentage, tax percentage, and additional fees. Then, it calculates the total cost based on these inputs.


HTML Structure

Here’s the basic structure of the HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Discount Calculator</title>
    <style>
        /* CSS styles go here */
    </style>
</head>
<body class="discount-body">

    <h1 class="discount-heading">Advanced Discount Calculator</h1>

    <div class="container discount-container">
        <!-- Form Inputs -->
        <label for="currency" class="discount-label">Currency:</label>
        <select id="currency" class="discount-select">
            <option value="$">USD ($)</option>
            <option value="€">EUR (€)</option>
            <option value="£">GBP (£)</option>
            <option value="₹">INR (₹)</option>
        </select>

        <label for="original-price" class="discount-label">Original Price (per item):</label>
        <input type="number" id="original-price" class="discount-input" placeholder="Enter original price" required>

        <!-- More form inputs... -->
        <button class="discount-button" onclick="calculateDiscount()">Calculate</button>

        <div id="discount-result" class="result discount-result"></div>
    </div>

    <script>
        // JavaScript functions go here
    </script>

</body>
</html>

Explanation:

  1. DOCTYPE and HTML Tags: The <!DOCTYPE html> declaration defines the document type, which is HTML5 in this case. The <html> tag contains all the HTML content.

  2. Head Section: Inside the <head> tag, we have meta tags for setting the character set and viewport for responsiveness. The title tag defines the title of the page displayed in the browser tab.

  3. Body Section: The body of the page contains the actual content that users will interact with. Here, we use an h1 tag for the main heading and a div for the container that holds the form elements.


CSS Styling

Now, let's talk about the CSS that styles the calculator:

body.discount-body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 20px;
    background-color: #f3f4f6;
    color: #333;
    box-sizing: border-box;
}

Breakdown:

  • body.discount-body: We apply general styles for the body, such as setting the font family to Arial, adding padding around the content, and setting a light background color. The box-sizing: border-box; ensures that padding and borders are included in the element's total width and height.
h1.discount-heading {
    text-align: center;
    color: #28a745;
    margin-bottom: 15px;
    font-size: 24px;
}
  • h1.discount-heading: The heading is centered, with a green color (#28a745), a margin at the bottom, and a font size of 24px.
.container.discount-container {
    max-width: 500px;
    margin: 0 auto;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border: 2px solid #28a745;
}
  • .container.discount-container: This section styles the container where all the form inputs and buttons are located. It has a maximum width of 500px, centered horizontally with margin: 0 auto;, and a green border. The box-shadow creates a subtle shadow around the container to give it depth.

JavaScript Functionality

The main functionality of the calculator is handled by JavaScript. Here's the calculateDiscount function:

function calculateDiscount() {
    const currency = document.getElementById('currency').value;
    const originalPrice = parseFloat(document.getElementById('original-price').value);
    const quantity = parseInt(document.getElementById('quantity').value);
    const discountPercentage = parseFloat(document.getElementById('discount-percentage').value);
    const taxPercentage = parseFloat(document.getElementById('tax-percentage').value);
    const additionalFees = parseFloat(document.getElementById('additional-fees').value);
    const resultDiv = document.getElementById('discount-result');
    
    if (
        isNaN(originalPrice) ||
        isNaN(quantity) ||
        isNaN(discountPercentage) ||
        isNaN(taxPercentage) ||
        isNaN(additionalFees)
    ) {
        alert('Please fill in all the fields with valid values.');
        return;
    }

    const totalOriginalPrice = originalPrice * quantity;
    const discountAmount = (totalOriginalPrice * discountPercentage) / 100;
    const discountedPrice = totalOriginalPrice - discountAmount;
    const taxAmount = (discountedPrice * taxPercentage) / 100;
    const finalPrice = discountedPrice + taxAmount + additionalFees;

    resultDiv.innerHTML = `
        <p><strong>Original Price:</strong> ${currency}${totalOriginalPrice.toFixed(2)}</p>
        <p><strong>Discount Amount:</strong> ${currency}${discountAmount.toFixed(2)}</p>
        <p><strong>Tax Amount:</strong> ${currency}${taxAmount.toFixed(2)}</p>
        <p><strong>Additional Fees:</strong> ${currency}${additionalFees.toFixed(2)}</p>
        <p><strong>Final Price:</strong> ${currency}${finalPrice.toFixed(2)}</p>
    `;
    resultDiv.style.display = 'block';
}

Breakdown:

  1. Element Selection: We use document.getElementById() to retrieve the values from the form inputs.
  2. Validation: We check if the input values are valid numbers. If any value is invalid, we show an alert to the user.
  3. Calculation: The total price is calculated by multiplying the original price by the quantity. We then apply the discount, calculate the tax, and add any additional fees.
  4. Display Results: The results are displayed in a div with the id discount-result. We use .innerHTML to dynamically update the content, and .style.display = 'block' to show the result.

Suggestions for Improvement 💡

The code works well, but there are always opportunities for improvement. Here are a few suggestions:

  1. Validation for Non-Negative Numbers: Make sure the user cannot input negative numbers for prices, quantity, or fees.
  2. Optional Tax and Fees: You could make the tax and additional fees fields optional by setting default values or adding more sophisticated input handling.
  3. User Feedback: Instead of an alert for invalid input, consider displaying a message within the page itself, which is less intrusive.

Share Your Thoughts 💬

What other improvements do you think could be made to this code? Drop your suggestions in the comments below and let’s make this calculator even better!


Test the Code Here 🔗

Test the Code


beginners Article's
30 articles in total
Beginner-friendly resources provide step-by-step guidance and foundational knowledge for those new to coding or technology.
Favicon
7 Developer Tools That Will Boost Your Workflow in 2025
Favicon
Creating a live HTML, CSS and JS displayer
Favicon
Build Your First AI Application Using LlamaIndex!
Favicon
Creating Arrays with Reference Variables
Favicon
How To Build Beautiful Terminal UIs (TUIs) in JavaScript 2: forms!
Favicon
The Great Failure of 2024
Favicon
Cómo Iniciar y Crecer como Desarrollador Frontend en 2025
Favicon
Chronicles of Supermarket website
Favicon
Building a Serverless REST API with AWS Lambda and API Gateway
Favicon
ruby -run
Favicon
Day 04: Docker Compose: Managing multi-container applications
Favicon
From "Never Engineering" to "Why Not?"
Favicon
From Bootcamp to Senior Engineer: Growing, Learning, and Feeling Green
Favicon
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained
Favicon
How to Resolve the 'Permission Denied' Error in PHP File Handling
Favicon
Introduction to Terraform: Revolutionizing Infrastructure as Code
Favicon
2025: The Year of Decentralization – How Nostr Will Make You a Standout Developer
Favicon
Amazon S3 vs. Glacier: Data Archival Explained
Favicon
What is Next Js: A Beginner's guide to Next Js
Favicon
Debugging Adventure Day 1: What to Do When Your Code Doesn’t Work
Favicon
Top 5 SaaS Trends for 2025
Favicon
Easy 301 Redirects For SEO
Favicon
How to Choose the Right Shopify Theme for Your Business Needs
Favicon
Булеві типи і вирази
Favicon
ruby -run, again
Favicon
Build a Secure Password Generator with Javascript
Favicon
5 Fun Projects to Master ES6 Javascript Basics in 2025 🚀👨‍💻
Favicon
got Tired of analysis paralyysis so i built an extensioon to get into flow faster
Favicon
Survival Manual: How to Create and Manage a Project in Git
Favicon
badly I want to know how to code😭😭

Featured ones: