Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Thursday, April 19, 2018

Simple JavaScript code to design calculator

For creating a basic calculator in JavaScript, we use table structure, input type button, and JavaScript functions.


  • Input type button use is to take input from the user.
  • The table structure use is to create calculator structure.
  • Functions to evaluate the data.



Three simple functions to process all data

Script

1. element()
Which is used to read values from each button

function element(val){
document.getElementById('result').value+=val;
}


2. solve()
This function performs all arithmetic operations like(+,-,/,*)

function solve(){
var value1= document.getElementById('result').value;
let res = eval(value1);
document.getElementById('result').value=res;
}


3. clearElement()
Which is used to clear input value in the calculator 

function element(val){
document.getElementById('result').value+=val;
}

HTML


<body>
<div id='wrap'>
<table border="1">
<tr>
<td colspan="3"><input type="text" id="result" readonly></td>
<td><input type="button" value="C"  onClick="clearElement()"></td>
</tr>
<tr>
<td><input type="button" value="1" onClick="element('1')"></td>
<td><input type="button" value="2" onClick="element('2')"></td>
<td><input type="button" value="3" onClick="element('3')"></td>
<td><input type="button" value="+" onClick="element('+')"></td>
</tr>
<tr>
<td><input type="button" value="4" onClick="element('4')"></td>
<td><input type="button" value="5" onClick="element('5')"></td>
<td><input type="button" value="6" onClick="element('6')"></td>
<td><input type="button" value="-" onClick="element('-')"></td>
</tr>
<tr>
<td><input type="button" value="7" onClick="element('7')"></td>
<td><input type="button" value="8" onClick="element('8')"></td>
<td><input type="button" value="9" onClick="element('9')"></td>
<td><input type="button" value="/" onClick="element('/')"></td>
</tr>
<tr>
<td><input type="button" value="*" onClick="element('*')"></td>
<td><input type="button" value="0" onClick="element('0')"></td>
<td><input type="button" value="." onClick="element('.')"></td>
<td><input type="button" value="=" onClick="solve()"></td>
</tr>
</table>
</div>
</body>

CSS


<style type="text/css">
body,html{
matgin:0px;
}
input[type="button"]{
border:none;
width:100%;
outline: none;
}
#wrap
{
margin:10%;
}
</style>



4 comments:

More Posts

FOLLOW