INTRODUCTION
NOT REALLY THAT EASY?
Welcome to a basic Javascript tutorial on how to add two numbers. Ha. How difficult can it be to add two numbers together? It should be a piece of cake now, right? Well, not really. Beginners usually run into a couple of problems – How to add numbers from textboxes, prompt boxes, and why numbers get concatenated together instead.
So here it is, this guide will help to answer some of these age-old questions by giving some examples. Read on!
I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
CONFESSION
AN HONEST DISCLOSURE
Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!
NAVIGATION
TABLE OF CONTENTS
Section A | Section B | Extra |
Closing |
SECTION A
TEXTBOX ADD
Let us now start with the simple and classic “how to get the values from HTML text boxes and add them together”.
THE HTML
Textbox Add Numbers Demo
The HTML part is super straightforward, Just create a simple form and 2 text fields – But remember to give the text fields different IDs so that we can find them with Javascript later.
THE JAVASCRIPT
function add () {
// Get the value of the text boxes
var x = document.getElementById("varX").value;
var y = document.getElementById("varY").value;
// Add them together
var z = x + y;
alert(z); // !! 35 !!
// This will stop the form from being submitted.
// * Stop the page from refreshing.
return false;
}
Yep, that’s all to the Javascript. Get the text boxes with document.getElementById()
, and access the .value
property.
THE RESULT
WHAT THE HECK IS HAPPENING!?
So… 3 plus 5 should be 8, and why did it become 35? Well, remember that Javascript is a loosely typed language? When we get the value from a text field, it is a string data type by default:
function add () {
// Get the value of the text boxes
var x = document.getElementById("varX").value;
var y = document.getElementById("varY").value;
console.log(typeof x); // string
console.log(typeof y); // string
// Therefore, we are actually concatenating the strings together here.
var z = x + y;
alert(z); // !! 35 !!
return false;
}
THE FIX
Now that you know the mystery behind the “hiccup”, there are 2 ways that we can fix it:
- By using
instead, to enforce a number input.
- By “converting” the string to integer or float in Javascript.
Textbox Add Numbers Demo
function add () {
// Get the value of the text boxes
var x = document.getElementById("varX").value;
var y = document.getElementById("varY").value;
// "Convert" string to integer
x = parseInt(x);
y = parseInt(y);
// Alternatively, use parseFloat if you want decimals
// x = parseFloat(x);
console.log(typeof x); // number
console.log(typeof y); // number
// This is correct now
var z = x + y;
alert(z); // 8
return false;
}
THE FIXED RESULT
SECTION B
PROMPT ADD
Now that you know the secrets behind how to add two numbers, we can simply do the same with prompt.
THE HTML
Prmopt Add Numbers Demo
Nothing much here, just a button to trigger the prompts.
THE JAVASCRIPT
function add () {
// The prompts
var x = prompt("Please enter the first nunmber", "5");
var y = prompt("Please enter the second nunmber", "3");
// Check and "convert" string to integer
if (isNaN(x) || isNaN(y)) {
alert("Invalid Input");
} else {
x = parseInt(x);
y = parseInt(y);
}
console.log(typeof x); // number
console.log(typeof y); // number
// The result
var z = x + y;
alert(z); // 8
}
Yep, you expert code ninjas should know what this does now. But here is one more tiny nugget of knowledge – We cannot restrict the user from entering alphabets here, so we can use the is-not-a-number isNaN()
function here to check for valid inputs.
THE FIXED RESULT
EXTRA
DOWNLOAD & SUMMARY
That’s all for the code, and here is the download link as promised – Plus a summary of the guide.
THE SUMMARY
- Create a simple form, HTML input text fields with unique IDs.
- Instead of using
, you can use
to restrict numbers only.
- To “enable” decimals add a
step
property to the input field. - You can get the element with
document.getElementById()
. - Fetch the value with the
.value
property. - By default, the retrieved value is of a string data type.
- Use
parseInt
orparseFloat
to “convert” into the number data type. - Finally, we can use the
isNaN()
function to check for invalid inputs.
EXAMPLE CODE DOWNLOAD
Click here to download all the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
CLOSING
WHAT’S NEXT?
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand the basic mechanics of Javascript, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
The post How to Add Two Numbers in Javascript appeared first on Code Boxx.