Sunday, March 13, 2016

Strictly JavaScript Income Tax Calculator


This example explains how to use the right conditions at right place.

"use strict"; //  undeclared variables prohibited.
var $ = function (id) {
    return document.getElementById(id);
};



window.onload = function () {
    $("calculate").onclick = calculateTax;
    $("reset").onclick = resetInputValues;

};
// this method is called on click of reset button
function resetInputValues() {
    $("tax").value = "";
    $("income").value = "";
    $("mymessage").innerHTML = "";
    return;
}

// this method is called on click of calculate button
function calculateTax() {
    //input validation
    var mySalary = $("income").value.trim();
    if (isNaN(mySalary)) {
        window.alert("Invalid input.");
        return;
    }
    mySalary = parseFloat(mySalary);

    var taxPaid = 0;

    if (mySalary > 413200) {
        taxPaid = (mySalary - 413200) * 0.396 + 119996.25;
    }
    else if (mySalary > 411500) {
        taxPaid = (mySalary - 411500) * 0.35 + 119401.25;
    }
    else if (mySalary > 189300) {
        taxPaid = (mySalary - 189300) * 0.33 + 46075.25;
    }
    else if (mySalary > 90750) {
        taxPaid = (mySalary - 90750) * 0.28 + 18481.25;
    }
    else if (mySalary > 37450) {
        taxPaid = (mySalary - 37450) * 0.25 + 5156.25;
    }
    else if (mySalary > 9225) {
        taxPaid = (mySalary - 9225) * 0.15 + 922.50;
    }
    else {
        taxPaid = mySalary * 0.10;
    }

    $("tax").value = taxPaid.toFixed(2);
    $("mymessage").innerHTML = taxPaid + " is rounded to " + $("tax").value;

}



No comments:

Post a Comment