×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript code to design calculator

In this JavaScript program, we are going to learn how to create a basic calculator? Here, we are create a basic calculatorfor that we are using eval JavaScript function and user define function.
Submitted by Ashish Varshney, on March 18, 2018

Description

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

  • Input type button use to take input from user.
  • Table structure is use to create calculator structure.
  • Eval function to evaluate the function.

The output

The output looks like...

Calculator in JavaScript

Code to design Calculator

<html>
<head>
	<script>
		
		function d(val){
			document.getElementById('result').value+=val;
		}
		function solve(){
			var value1= document.getElementById('result').value;
			let res = eval(value1);
			document.getElementById('result').value=res;	
		}
		functioncleard(){
		document.getElementById('result').value="";
		}
			
	</script>

	<style type="text/css">
		body,html{
			matgin:0px;
		}
		input[type="button"]{
			border:none;
			width:100%;
			outline: none;
		}
		#wrap
		{
			margin:10%;
		}
	</style>
</head>
<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="cleard()"></td>
		</tr>
		<tr>
			<td><input type="button" value="1" onClick="d('1')"></td>
			<td><input type="button" value="2" onClick="d('2')"></td>
			<td><input type="button" value="3" onClick="d('3')"></td>
			<td><input type="button" value="+" onClick="d('+')"></td>
		</tr>
		<tr>
			<td><input type="button" value="4" onClick="d('4')"></td>
			<td><input type="button" value="5" onClick="d('5')"></td>
			<td><input type="button" value="6" onClick="d('6')"></td>
			<td><input type="button" value="-" onClick="d('-')"></td>
		</tr>
		<tr>
			<td><input type="button" value="7" onClick="d('7')"></td>
			<td><input type="button" value="8" onClick="d('8')"></td>
			<td><input type="button" value="9" onClick="d('9')"></td>
			<td><input type="button" value="/" onClick="d('/')"></td>
		</tr>
		<tr>
			<td><input type="button" value="*" onClick="d('*')"></td>
			<td><input type="button" value="0" onClick="d('0')"></td>
			<td><input type="button" value="." onClick="d('.')"></td>
			<td><input type="button" value="=" onClick="solve()"></td>
		</tr>
	</table>
	</div>
</body>
</html>

JavaScript Examples »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.