Nuffnang Ads

Thursday, 4 September 2014

Simple calculator using Javascript - part 2

From the previous post, we already know how to create a simple calculator using javascript, but the problem is, it only support addition operation. We need to do some modification to make it support other mathematical operations i.e. subtraction, multiplication,division. Something similar like shown in the picture below :-


1) Use the existing code from previous post.
2) Add another buttons and make sure it will redirect to the right function.

 <input type="button" value="-" name"but2" onClick="subNum()">
<input type="button" value="x" name"but3" onClick="mulNum()">
<input type="button" value="/" name"but4" onClick="divNum()">

3) Create additional function to support the additional mathematical operations.

function subNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1-num2;
document.frmadd.txt3.value=num3;
}
function mulNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1*num2;
document.frmadd.txt3.value=num3;
}
function divNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1/num2;
document.frmadd.txt3.value=num3;
}

4) Save and Run.
Example for the division operation

5) Here is the full code:-

<html>
<body>
<h3> Simple Calculator </h3>
<script language="JavaScript">

function addNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1+num2;
document.frmadd.txt3.value=num3;
}
function subNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1-num2;
document.frmadd.txt3.value=num3;
}
function mulNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1*num2;
document.frmadd.txt3.value=num3;
}
function divNum()
{
num1=parseInt(document.frmadd.txt1.value);
num2=parseInt(document.frmadd.txt2.value);
num3=num1/num2;
document.frmadd.txt3.value=num3;
}
</script></head><body>
<form name="frmadd">

Num1<input type ="text" name="txt1" ><br>
Num2<input type ="text" name="txt2" ><br>
Result<input type ="text" name="txt3" disabled><br>

<input type="button" value="+" name"but1" onClick="addNum()">
<input type="button" value="-" name"but2" onClick="subNum()">
<input type="button" value="x" name"but3" onClick="mulNum()">
<input type="button" value="/" name"but4" onClick="divNum()">

</form>
</body></html>

No comments:

Post a Comment