Addition of Two Numbers Using Js

In this program we use javascript for addition in form.By collecting number by id convert into numbers.Then using addition operator,display result on div by InnerHTML.

Code

<!DOCTYPE html>
<html lang="en">
   <head>
<title>Addition of Two Numbers Using Forms with JavaScript | Ahirlabs Programs Demo </title>
<head>
<body>
<form method="post">
			<p> Enter First Value : <input type="text" name="val_1" id="val_1"  /></p>
			<p>Enter Second Value :<input type="text" name="val_2" id="val_2" /></p>
			<p><input type="button" name="add" value="Add" onclick="sum()">
<input type="reset" name="clear" value="Clear" /></p>
		</form>
		
            <div id="result" class="result"></div>



<script type="text/javascript">
	function sum() {
var a,b,c;
a = Number(document.getElementById("val_1").value);
b = Number(document.getElementById("val_2").value);
		if (a == 0 && b == 0) {
			alert("Please Enter a Number Greater Than Zero");
		} else {
c = a + b;
			document.getElementById("result").innerHTML = "</p>
<p> Result of  " + a + "+" + b + "=" + c + "</p>
<p>";
		}
	}
		</script>
</body>
</html>

Explanation

Step 1. First make form with define with id. Like val_1 & val_2.
Step 2. Button for trigger the function which calculate the values by using onclick=”sum()”
Step 3. Make function name of sum()
Step 4. Declare variable a,b,c; Like var a,b,c; 
Step 5. document.getElementById(“val_1”).value is for get value by id. Like number text. Note id is same to collect info.
Step 6. Number() convert any value to number.If any text its tell zero.
Step 7. Validation by if A & B value is zero then alert(“Please Enter a Number Greater Than Zero”)
Step 8. document.getElementById(“result”).innerHTML is for display the result on div after completed.
Step 9. innerHTML is property which add text between Tags.LIKE  <div id=”result”>  Text </div>  or <p id=”result”>Text</p>.

Demo


demo

(Visited 148 times, 1 visits today)
Share with Friends :
Written by:

Leave a Reply

Your email address will not be published. Required fields are marked *