Adding Two numbers
This post focuses on adding two numbers, adding two numbers does not mean static value but dynamic inputs with a simple number validation. Below is the step by step procedure.
Create a index.html and place the below code in the body section of the HTML file.
<!DOCTYPE HTML>
<head>
<title>Add two numbers</title>
<script type="text/javascript" src="script.js" >
</head>
<body>
Enter the first number: <input type="text" id="txt1" /><br />
Enter the seccond number: <input type="text" id="txt2" /><br />
<input type="button" onclick="call()" value="Add"/>
</body>
</html>
Create a javascript file(script.js) with the below content.
function call(){
var q=parseInt(document.getElementById("txt1").value);
var w=parseInt(document.getElementById("txt2").value);
var result=q+w;
if(isNaN(q)||isNaN(w)){
alert("please enter a number");
}
else
{
var result=q+w;
alert("The sum is " +result);
}
}
Please do not forget to include the javascript file(script.js) in the index.html.
In this example you would have observed the following javascript terms.
- onclick
- document.getElementById
- parseInt
- isNaN
1. onclick-In the above example onclick it calls the function call();
2. document.getElementById -gets the values entered in the input fields which defined with id's txt1 and txt2.
3.parseInt - converts the value to Int type.
4.isNaN - checks if the value is NaN.
Couple of things to be noted
- document.getElementById always returns a string value, so we need to convert the value to Int(parseInt) for mathematical operations.
- In order to ensure that the entered inputs are only numbers , a if condition is implemented to check the values. If the entered value is not a number then it would alert with(please enter a number).
Thorough this example we can add dynamic inputs and validate.
Hope this post was informative, would be adding some more post shortly.