Write a Javascript program to print maximum number between 2 numbers?

Find the below code to print maximum number from 2 numbers in javascript.

Simple Idea

var a = 56,
    b = 67;

var max = (a > b) ? a : b;

console.log("The maximum number is "+ max);

Developed Idea

View Demo: http://www.gtvcreations.com/demo/js-print-max-from-two-numbers.html

View Code:

<!DOCTYPE html>
<html>

<head>
    <title>Print Maximum Number between Two Numbers - Javascript</title>
</head>

<body>
    <!-- Input Form -->
    <form id="findmaxform">
        <label for="number1">Number 1:</label>
        <input type="number" id="number1">
        <br>
        <label for="number2">Number 2:</label>
        <input type="number" id="number2">
        <br>
        <input type="submit" value="Print Maximum Number">
        <input type="reset" value="Reset Form">
    </form>

    <!-- Display Calculated Values -->
    <div id="result" style="display: none;">
        The maximum number is <b id="max"></b>
    </div>

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

            // Reset to Array Array
            var max = 0;

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

            // Logic - Compare value of all input elements
            for (var i = 0; i < inputElements.length; i++) {
                // Check it is not NaN
                if (!isNaN(Number(inputElements[i].value))) {
                    // Compare and Assign Value to `max` Variable
                    max = (max > Number(inputElements[i].value)) ? max : inputElements[i].value;
                }
            }

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

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

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

</html>

Note: If you want to print maximum from more than two numbers just add input field inside the form.

Comments

Popular posts from this blog

About 12 Alwars

Post thumbnails from external URLs don’t appear in Blogger. How to resolve?