Site Loader
Get a Quote

add two numbers in JavaScript

add two numbers in JavaScript using Textbox

add two numbers in JavaScript: Hi Readers, In javascript adding two numbers, is very easy and basic steps to learn javascript.We take two numbers from textbox and display result of the sum of two numbers.

add two numbers in JavaScript

First of all, We will create a two text box and get the value of textbox using document.getElementById(“sum1”).value;  .This javascript code will get the value of textbox entered by users and save in variables defined by var.Here we have used a parseInt function to convert to int so that string concatenation couldn’t possible.

We have used return statement of javascript so that when we call the function and it could return the value on calling the function.

Suppose we have created a function with sum() and put the logic inside the function and return the sum of any two numbers on when users click the button.We have used also document.write function.This function is used to print a statement in javascript.

add two numbers using textbox Source Code

<!doctype html>
<title>add two numbers in JavaScript</title>
<!--Javascript code starts-->
<script type="text/javascript">

//function is created using function keyword.
function add()
var x=document.getElementById("sum1").value;
//getElementById get the value of element with id=sum1.

var y=document.getElementById("sum2").value;
//getElementById get the value of element with id=sum2.

var sum=parseInt(x) + parseInt(y); //addition of two values
//parseInt is used to convert the string into integer type.
return sum;
//return statement is used to return the value.

<!--javascript code ends -->


<input type="text" name="text1" id="sum1"/>
<input type="text" name="text2" id="sum2" />
<button type="button" onclick="document.write(add());">Output</button>

<!--onclick()event is used to display the value of add()when user clicks the button -->


I hope you would like this post about add two numbers in JavaScript using Textbox with return statement


Post Author: TechieFlair

Leave a Reply

Your email address will not be published.