Tuesday, November 20, 2012

Building calculator using javascript function

Code:
<script type=”text/javascript”>
function add()
{
var first=parseInt(document.getElementById(‘first’).value);
var second=parseInt(document.getElementById(‘second’).value);
var third=document.getElementById(‘answer’);
answer.value= first + second;
}
function subtract()
{
var first=parseInt(document.getElementById(‘first’).value);
var second=parseInt(document.getElementById(‘second’).value);
var third=document.getElementById(‘answer’);
answer.value= first – second;
}
function multiply()
{
var first=parseInt(document.getElementById(‘first’).value);
var second=parseInt(document.getElementById(‘second’).value);
var third=document.getElementById(‘answer’);
answer.value= first * second;
}
function divide()
{
var first=parseInt(document.getElementById(‘first’).value);
var second=parseInt(document.getElementById(‘second’).value);
var third=document.getElementById(‘answer’);
answer.value= first / second;
}
</script>
<table width=”250″ border=”0″ align=”center” >
<tr>
<th width=”100″ scope=”row”>First no:</th>
<td width=”140″><input type=”text” name=”first” id=”first”>&nbsp;</td>
</tr>
<tr>
<th scope=”row”>Second no:</th>
<td><input type=”text” name=”second” id=”second”></td>
</tr>
<tr>
<th colspan=”2″ scope=”row”>
<input type=”submit” name=”add” value=”+” onClick=”add();”>
<input type=”submit” name=”subtract” value=”-” onClick=”subtract();”>
<input type=”submit” name=”multiplication” value=”*” onClick=”multiply();”>
<input type=”submit” name=”division” value=”/” onClick=”divide();”>
</th>
</tr>
<tr>
<th scope=”row”>Total</th>
<td><input type=”text” id=”answer”></td>
</tr>
</table>
Output:

No comments:

Post a Comment