I want to add keyboard support to my calculator. When i press operations with keyboard (i.e. +,-,* or /) js sees it as number, not as operation.
For example, when I com
Give this a shot. It's not got any functionality for delete key or arrow keys, but it will perhaps help move you forward more.
An explanation of the code:
The getValue routine does the bulk of fixing things up, and answers the key points in your original question:
If a variable is being interpreted as of type string it can mess up the computation. So you can convert a variable you don't know the type of to string by combining an empty string with the variable itself.
There is code to check for the existence of a decimal point, then use either parseFloat or Number to cast the type of the variable (parseInt is a more verbose alternative, needing radix of 10 - for a base 10 number).
A couple of other key variables are:
There is also some funky stuff going on, mimicking a normal calculator. So that when computation goes on, you can do something like enter:
So the last number you enter becomes like a 'sticky' constant in memory. Whenever a new value gets entered, that becomes the new 'sticky' value. So:
So: - the values array is used to store both the sticky value and the total:
+
, -
, /
, *
or =
is pressed. checkCalcKey() is an event handler for onkeydown upon the input HTML control's. By returning false
, it prevents the character you type from build input. Instead it defers to the click handler of the corresponding button and any character entry into the input control value property gets performed via that handler instead. (More info here).