Thursday, January 30, 2020

Write a program to calculate the sum and percentage using Javascript?

Find the below code to calculate sum and percentage of 3 subjects in javascript.

Simple Idea

var subjectMarks = [56, 67, 78];
var total = 0,
    percentage = 0;

for(var i=0; i<subjectMarks.length; i++) {
    total += subjectMarks[i];
}

percentage = total / subjectMarks.length;

console.log("Sum: " + total + "\nPercentage: " + percentage.toFixed(2));

Developed Idea

View Demo: http://www.gtvcreations.com/demo/js-calculate-sum-percentage.html

View Code:

<!DOCTYPE html>
<html>

<head>
    <title>Calculate Sum and Percentage of Three Subjects - Javascript</title>
</head>

<body>
    <!-- Input Form -->
    <form id="markcalcform">
        <label for="subject1">Subject 1:</label>
        <input type="number" id="subject1">
        <br>
        <label for="subject2">Subject 2:</label>
        <input type="number" id="subject2">
        <br>
        <label for="subject3">Subject 3:</label>
        <input type="number" id="subject3">
        <br>
        <input type="submit" value="Calculate Sum & Percentage">
        <input type="reset" value="Reset Form">
    </form>

    <!-- Display Calculated Values -->
    <div id="result" style="display: none;">
        Sum: <b id="sum"></b>
        <br>
        Percentage: <b id="percentage"></b>
    </div>

    <!-- Javascript -->
    <script>
        // Show Result Function
        function showResult(event) {
            // Prevents Page Reload on Submit
            event.preventDefault();

            // Reset to Array Array
            var sum = 0;

            // Get all Input Elments in array
            var inputElements = this.querySelectorAll("input[type='number']");

            // Logic - Sum value of input elements
            for (var i = 0; i < inputElements.length; i++) {
                sum += parseInt(inputElements[i].value);
            }

            document.getElementById("sum").innerHTML = sum + " / " + (inputElements.length * 100);
            document.getElementById("percentage").innerHTML = (sum / inputElements.length).toFixed(2) + " %";

            document.getElementById("result").style.display = "block";
        }

        // Clear Result
        function clearResult() {
            document.getElementById("result").style.display = "none";
        }

        // Add Submit and Reset Event
        document.getElementById("markcalcform").addEventListener("submit", showResult);
        document.getElementById("markcalcform").addEventListener("reset", clearResult);
    </script>
</body>

</html>

Note: If you want to calculate sum and percentage for more than three subjects just add input field inside the form.

No comments:

Post a Comment