Hello all,

I am looking for a bit of code to make an input field into a calculator. The main difference from most scripts is I want it with no buttons. I am hoping to use the number pad on the keyboard.

So, for example, I would like an input box where I could type "2.57*.25+3.61/5" and press enter and have the text box filled with the correct answer. I'm assuming this will have to be processed with onkeypress.

If anyone has a suggestion or a bit of code I would be grateful.

Thanks

You can improve the following code

<html>
	<head>
		<script>
			document.onkeydown = function(e)
			{
				e = e? e : window.event;
				var k = e.keyCode? e.keyCode : e.which? e.which : null;
				if (k == 13)
				{
					if (e.preventDefault)
					e.preventDefault();
					return false;
				}
				return true;
			};

			function process(e)
			{
				if(e.keyCode == 13)
				{
					calculate()
				}
			}

			function calculate()
			{
				var answer = 0;
				eval("answer = "+document.getElementById("cal_display").value);
				document.getElementById("cal_display").value = answer
			}
		</script>
	</head>
	<body>
		<form id="calform" name="calform">
			<input id="cal_display" name="cal_display" value="" onkeypress="process(event);">
		</form>
	</body>
</html>

Here's a jquery solutuon:

$(function(){
	$r = $("#calculator").find("#result");
	$ip = $("#calculator").find("#input");
	$("#calculator").find("button").click(function(){
		try{ $r.html( eval($ip.val()) ); }
		catch(e){ $r.html('Error'); }
	}).click();
});
* { font-family:verdana; font-size:10pt; }
#calculator { width:650px; padding:10px; border:2px solid #999; }
#calculator input { margin-right:10px; }
#calculator button{ margin-right:10px;  }
#calculator span { border:1px solid #999; padding:2px 4px; }
<div id="calculator">
	<input value="0"><button>=</button><span id="result"></span>
</div>

Airshow

Thanks for the help niranga. Your code worked perfect. I knew it couldn't be that hard. Thanks again.

Welcome :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.