Add multiple integer values using JavaScript in html

Mohammed Imtiyaz Jun 5, 2014

In this tutorial we will learn how to calculate the sum of multiple integers using JavaScript. The main reason behind using JavaScript for calculating multiple integers is, the code executes at the client side without the full page postback.

Live Demo

HTML Controls

We need to call this JavaScript function on OnKeyUp event of the input controls.

<!DOCTYPE html>
<html>
<body>
    <label for="txtValue1">Value 1:</label>
    <input type="text" id="txtValue1" placeholder="0" onKeyUp="javascript:Add();">

    <label for="txtValue2">Value 2:</label>
    <input type="text" id="txtValue2" placeholder="0" onKeyUp="javascript:Add();">

    <label for="txtValue3">Value 3:</label>
    <input type="text" id="txtValue3" placeholder="0" onKeyUp="javascript:Add();">

    <label for="txtValue4">Value 4:</label>
    <input type="text" id="txtValue4" placeholder="0" onKeyUp="javascript:Add();">

    <label for="txtTotal">Total:</label>
    <input type="text" id="txtTotal" placeholder="0">
</body>
</html>

To make these controls work, we need to write a small JavaScript function.

<script language="javascript" type="text/javascript">
    function Add() {
        var val1, val2, val3, val4;

        // If input value is null, then the below mentioned if condition will 
        // come into picture and make the value to '0' to avoid NaN Error.

        val1 = parseInt(document.getElementById("txtValue1").value);
        if (isNaN(val1) == true) {
            val1 = 0;
        }

        var val2 = parseInt(document.getElementById("txtValue2").value);
        if (isNaN(val2) == true) {
            val2 = 0;
        }

        var val3 = parseInt(document.getElementById("txtValue3").value);
        if (isNaN(val3) == true) {
            val3 = 0;
        }

        var val4 = parseInt(document.getElementById("txtValue4").value);
        if (isNaN(val4) == true) {
            val4 = 0;
        }

        document.getElementById("txtTotal").value = val1 + val2 + val3 + val4;
    }
</script>