$(document).ready(function(){
var allowedKeys=[48,49,50,51,52,53,54,55,56,57, // 0 to 9 (keyboard)
96,97,98,99,100,101,102,103,104,105, // 0 to 9 (numpad)
111,106,109,107,110, // characters / * - + . (numpad)
189,190,8,32,13 // character - . [backspace] [space] [enter] (keyboard)
];
var allowedShiftKeys=[51,56,57,48,187,57,48,16]; // characters / * + ( ) [shift] (keyboard + shift)
$("input[name='equation']").on("keydown",function(e){
// Clear previous answer
$('#answer').html("");
// Check for allowed keydown
if( ($.inArray( e.which,allowedKeys) != -1 && !e.shiftKey) || ($.inArray(e.which,allowedShiftKeys)!=-1 && e.shiftKey) ){
console.log("Allowed key.");
}else{
// Don't print the key in the input field.
console.log("Disllowed key.");
e.preventDefault();
// Helper to find key number
console.log(e.which);
}
// [enter] handler to simulate a button click.
if(e.which==13){
$('button').click();
}
});
$('button').click(function(){
var InputtedValue = $("input[name='equation']").val();
// Remove "//" sequence... Which has the special meaning of a "comment start".
// Has to be removed before eval() works.
for(i=0;i<InputtedValue.length;i++){
var position = InputtedValue.indexOf("//");
if(position!=-1){
console.log('Removing "//" occurance.');
InputtedValue = InputtedValue.replace("//","/");
// Redo the loop from start.
i=0;
$("input[name='equation']").val(InputtedValue);
}
}
// Try the eval() function... And catch the error if any (Error will come from the inputted formula).
// Prevents the script from just jamming here.
try{
var answer = eval( InputtedValue );
}
catch(error){
console.log("ERROR: "+error.message);
}
// If there is an answer.
if(typeof(answer)==="number"){
$('#answer').html(answer);
}else{
$('#answer').html("Something is wrong in your equation.");
}
console.log("Answer: "+answer);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="equation" value="(5+6) * 7 -2"> = <span id="answer"></span>
<br>
<button>Calculate</button>