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

Dani AI

Generated

This thread already has two compact solutions: posted a minimal working answer and showed a jQuery alternative. Both are useful as quick fixes, but they evaluate raw input directly. The snippet below keeps the same single‑field UX (Enter to compute, numpad compatible) while adding a simple whitelist check and modern event handling to reduce the risk of executing arbitrary code.

// attach to the same input id used in the thread
const input = document.getElementById('cal_display');

input.addEventListener('keydown', function (ev) {
  if (ev.key === 'Enter' || ev.keyCode === 13) {
    ev.preventDefault();
    const expr = input.value.trim();
    if (!expr) return;

    // allow only digits, whitespace, parentheses, decimal point and arithmetic operators
    if (!/^[0-9\s+\-*\(\)\/\.%]+$/.test(expr)) {
      input.value = 'Error: invalid characters';
      return;
    }

    try {
      // evaluate the arithmetic expression (keeps evaluation scoped to the expression)
      const result = Function('"use strict"; return (' + expr + ')')();
      input.value = String(result);
    } catch (err) {
      input.value = 'Error';
    }
  }
});

Notes and troubleshooting: the regex intentionally rejects letters and other symbols; this blocks most injection attempts but is not a replacement for a full parser when inputs are untrusted. For advanced math (functions, variables, units) or when inputs come from other users, use a dedicated expression library. To avoid accidental form submissions, bind the handler to the form's submit and call preventDefault there as well. For mobile numeric keyboards, consider inputmode="decimal" on the field.

Summary: 's code is a good starting point. The above tweaks modernize the handler and add lightweight validation, keeping the same Enter/numpad flow while reducing the attack surface.

Recommended Answers

All 4 Replies

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.