Using try..catch
with eval()
I've created an unsafe example on JSFiddle that does what you require but instead of waiting for result when caret is still on the input box, I attached to blur
event so value gets evaluated when you switch focus outside of the control.
What it does is this:
$("input").blur(function(evt) {
try {
var val = eval(this.value);
this.value = val;
}
catch (e) {}
});
It tries to evaluate content of the input box and if it was able to do so, replace content with the result. This means that you can throw anything at it as long as eval
can chew on it.
I said unsafe, because code's not checking content for anything that could cause black holes to swallow universes... ;)
Examples
1 + 2 * 3
will change 7
universe
will leave it as universe
010+1
will change to 9 (so it groks octals as well)
0xf *2 +3
will return 33 (look ma' hex as well)
- etc.
Implement your way to make it safer
This is of course just a start. If you'd like x to be become multiplicator, you will have to do some replacements in input string, that my example doesn't do. But it's pretty straight forwards to do so.
The same is true if you'd only like to do particular calculations, so you don't allow creating objects or dates or anything...
An example that is likely undesirable in your case is if you'd type in
alert(new Date())
which would of course execute this code and display an alert box. Whether you'd like to allow this or not is on you. If you'd be posting original data to server yu'd of course want to sanitize inputs severely.