Before reading this article you should know about
- HTML Input
- HTML DOM
- Javascript Function
- HTML Button
- HTML onclick event.
In this tutorial, we will learn how to add two numbers in JavaScript using a textbox and display the sum of those numbers on another box.
Let’s understand the logic of the program.
Step 1: The two boxes are created which will be used for the user to enter the number. The code used is
Enter First Number:
<input type="text" id="Num1"><br /><br />
Enter Second Number :
<input type="text" id="Num2"><br /><br />
The output will look something like this.

Note: We used HTML input tag with the attribute type = “text” to get the text box.
Step 2: A button will be created. The code is
<button onclick = "Add()">Submit</button>
The button will look something like this.

When the user clicks this button the Javascript Add() function will be called.
Step 3: A third box called sum is created where the addition of two numbers is Placed. The code is
Sum : <input type="text" id="Sum">
Step 4: The add function will be executed.
function Add() {
var a = parseInt(document.getElementById("Num1").value);
var b = parseInt(document.getElementById("Num2").value);
var c = a + b;
document.getElementById("Sum").value = c;
}
The second and third lines of the above code will get the value entered by the user and pass it to variables a and b.
Since the value returned by the code document.getElementById(“Num1”).value is a string. The parseInt function will convert the string to an integer.
Step 5: After adding the two numbers the value will stored in the third box.
The complete code
HTML Code
<!DOCTYPE HTML>
<HTML>
<head>
<title>Javascript program to add two numbers using textbox
</title>
</head>
<body>
<h3> Javascript program to add two numbers using textbox</h3>
<div>
Enter First Number:
<input type="text" id="Num1"><br /><br />
Enter Second Number :
<input type="text" id="Num2"><br /><br />
<button onclick = "Add()">Submit</button><br /><br />
Sum : <input type="text" id="Sum">
</div>
</body>
</HTML>
Javascript Code
function Add() {
var a = parseInt(document.getElementById("Num1").value);
var b = parseInt(document.getElementById("Num2").value);
var c = a + b;
document.getElementById("Sum").value = c;
}
Type any two numbers in the boxes let’s say 5 and 4 and press submit. The output will be visible in the sum box. It will look something like this.
