HTML - Javascript calculator  

by ne on 2021-03-01 under Javascript

If you are looking for a pure html-javascript calculator having same feel, as your palm (but just for a beginner level).
The below might work for you:


<html>
	<head>
		<title>Naveen Soni</title>
		<script type="text/javascript">				
			var op='',first=0,second=0;
			var bar,setClear=false;
			function calculator(i){
				var p=parseInt(i);
				if(p>=0 && p<=9){if(setClear==true) bar.value="";  bar.value+=p; setClear=false;}
				else{
				first=parseInt(bar.value);
				setClear=true;
				op=i;
				}		
			}
			function showPad(){
				bar=document.getElementById("bar");
				var padList="";
				for(i=0;i<10;i++){if(i%3==0) padList+="<br>";  padList+="<button id='"+i+"' onclick='calculator("+i+")'>"+i+"</button>";}
				document.getElementById("theButtonPad").innerHTML=padList;
			}
			function calculate()
			{
				var result;
				second=parseInt(bar.value);
				switch(op)
				{
				case '+':  result=first+second; break;
				case '-':  result=first-second; break;
				case '*':  result=first*second; break;
				case '/':  result=first/second; break;
				default:
				first>=second?result=first:result=second;
				}
				bar.value=result;
			}
		</script>
	</head>
	<body onload="showPad()">
		<div style="margin-left:300px;text-align:center; background-color:lightyellow; width:300px;">
			<input type="text" id="bar"><br>
			<div id="theButtonPad">
			</div>
			<div id="operators">
			<button onclick="calculator('+')">+</button>
			<button onclick="calculator('-')">-</button>
			<button  onclick="calculator('*')">*</button>
			<button onclick="calculator('/')">/</button>
			<button  onclick="calculate()">=</button>
			<button onclick="document.getElementById('bar').value='';">C</button>
			<div>
		</div>
	</body>
</html>