0

For an HTML5/JavaScript learning experience I'd like to write a basic calculator. The first thing I need to know is what options are there in terms of input types which would support only numeric characters, and (if possible) allow the inclusion of operators such as + and -. The end result would be for the user to be able to input characters in the value range of 0-9, as well as {+, -, /, *, ... }.

Is there anything which is natively tailored to this kind of thing, or at the very least tweakable to something of that nature?

zeboidlund
  • 9,731
  • 31
  • 118
  • 180

1 Answers1

2

Here's simple calculator using eval and regex:

HTML:

<input type="text" id="calc">
<button id="calculate">Calculate</button>

JavaScript:

var input = document.querySelector('#calc')
  , button = document.querySelector('#calculate');

// Only allow numbers and operators
input.addEventListener('keypress', function(e) {
  var key = String.fromCharCode(e.which);
  if (!/[0-9+\-/*]+/.test(key)) e.preventDefault();
});

button.addEventListener('click', function() {
  alert(input.value +' = '+ eval(input.value));
});

Demo: http://jsbin.com/utujas/1/edit

Some say eval is evil, but it's fine for a simple calculator, otherwise you'd have to resort to something like this: javascript calculator: plus sign alternatives

Community
  • 1
  • 1
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • The fact that you use `if (!/[0-9+\-/*]+/.test(key))` makes `eval` perfectly fine here :) – Ian Jun 11 '13 at 15:30