In this tutorial, let’s look at how to add two numbers in JavaScript using a textbox. We’re going to start off by creating the HTML part of things.
The program’s skeleton – HTML
Let’s start with a header. I’m going to make it a simple header that says, “Add 2 numbers”, since that’s what our program is going to do.
<h1>Add 2 numbers</h1>
I’ll be focusing on the JavaScript aspect of things alone, so no styles for this program.
Right after the heading, I’ve created 2 input boxes with their own text labels. These input boxes have unique ids of ‘num1’ and ‘num2’, so we can later reference them from our JavaScript file.
Our user will be expected to enter the numbers they wanted added in these 2 boxes.
Enter the first number: <input id='num1' type="text" /> <br/> Enter the second number: <input id='num2' type="text" /> <br/>
We also need an ‘Enter’ button with a unique id ‘button’. On clicking this button, our script file will retrieve the numbers entered in the text boxes, perform the addition, and display the output in the empty div element (of id ‘output’) we’ve created right after.
<button id='button'>Enter</button> <div id="output"></div>
So, that’s it for the HTML part of things. Next, let’s populate our script file.
When you run it, you’ll get:
The logic of the program – JavaScript
While manipulating HTML elements, we need to retrieve them. One of the best ways to retrieve these elements is by using their unique identifier, and the getElementById method.
So, let’s do just that and retrieve our ‘num1’, ‘num2’, ‘button’ and ‘output’ elements and put them in constants of the same names. We’re placing these elements in constants since we’ll just be retrieving them in the future, but not manipulating them or changing their values in any way.
const num1 = document.getElementById('num1'); const num2 = document.getElementById('num2'); const button = document.getElementById('button'); const output = document.getElementById('output');
We also need 2 variables to store the retrieved numbers from the input boxes; these variables are ‘n1’ and ‘n2’, and we’re assigning them a 0 to start with.
The last variable we need is ‘sum’, assigned a starting value of 0, to which we’ll store the addition of the 2 given numbers.
let n1 = 0, n2 = 0, sum = 0;
Now, we need to create a click event listener on our button element. This event listener specifies that, when the given element, which is our button, is clicked on, we need something to happen. What needs to be happened can be mentioned in the form of lines of code inside a function.
In our case, we’re sticking to an anonymous arrow function. You can also just mention the name of the function as the second argument of our addEventLitener() function call and define the function separately.
button.addEventListener('click',() => {
Inside the anonymous arrow function, we’re going to finish the rest of the program because everything we need to happen should only happen once the button has been clicked.
Let’s start by parsing the values in our input boxes. Even though the users enter numbers, your input boxes will store them as strings by default. So, we need to convert them to integers by using the parseInt method, as shown below.
n1 = parseInt(num1.value,10); n2 = parseInt(num2.value,10);
I haven’t done any type checking above, but you can (and should) add lines of code to check whether the user has indeed entered a number.
One of the best ways to do that is by checking if the resultant value is a number by using the isNaN() method. The isNaN() method checks if the number is ‘not a number’ or not.
If the method returns true, we ask the user to re-enter values in the input box and break the function’s execution, as shown below. We need to re-set the text in the ‘output’ element so it can be used to display the result of the next operation though.
if(isNaN(n1) || isNaN(n2)) { alert('Please enter valid numbers'); output.innerText = ''; }
In the if condition above, we’ve used the OR (||) operator because if any of the numbers are NaN, we need to abort the program.
If we get a false, that means we have 2 numbers at hand, and we can go ahead with the addition. Once added, update the value of ‘sum’ in the ‘output’ element, as shown below:
else { sum = n1 + n2; output.innerText = `${n1} + ${n2} = ${sum}`; }
Finally, re-set the values of the input boxes and ‘sum’ for the next addition. We don’t need to re-set the value of ‘output’ here because it’s going to be replaced by the new value once the user clicks on the button anyway.
num1.value = ''; num2.value = ''; sum = 0;
Now, let’s test the app.
When you first run it, input 2 numbers, pressing on the button will get you the following result:
As you can see above, the minute I pressed ‘Enter’, the values I typed in the text boxes disappeared, and the string ’10 + 15 = 25’ appeared right below the button.
If you enter anything other than a number in the text boxes though, you’ll see something like this:
That’s it! This is how you can add two numbers in JavaScript using text boxes.