A jQueryplugin
that attaches a popup calculator to an input field.
The current version is 2.0.1 and is available
under the MIT licence.
For more detail see the documentation reference page.
Or see a minimal page that you could
use as a basis for your own investigations.
The calculator functionality can easily be added to a text field with appropriate
default settings.
You can also remove the calculator widget if it is no longer required.
Processed fields are marked with a class of is-calculator
and are not re-processed if targeted a second time.
Invocation
You can trigger the calculator by focus on the field (the default),
via an associated button, or by both. Alternately, the calculator
can appear only when a non-numeric character is entered into the field.
Disable or enable the fields and their triggers via a command.
You can also control the animation used to display the calculator and its duration.
There are three standard animations (show,
fadeIn, slideDown) as well as the ones from the
jQuery UI effects package.
Additional options for the latter may be specified with the
showOptions setting.
You can present the calculator inline by applying it to a div or
span. Make use of the value selected via the onClose
callback. You can click on the calculator or tab to it to give it focus,
at which point you can use the keyboard for entry as well.
Inline calculator:
$('#inlineCalc').calculator({onClose: useValue});
function useValue(value, inst) {
alert('The calculated value is ' + value);
}
$('#inlineDisable').click(function() {
var disable = $(this).text() === 'Disable';
$(this).text(disable ? 'Enable' : 'Disable');
$('#inlineCalc').calculator(disable ? 'disable' : 'enable');
});
You can alter the layout of the calculator by specifying the
keys per row as a string array. Each key is identified by
a two-character code or a named constant. The standard layout
is a predefined constant: $.calculator.standardLayout.
Set the showFormula option to display the formula being evaluated.
Listed below are the additional codes and constants
($.calculator.) for the scientific calculator keys.
Code
Constant
Function
'_%'
PERCENT
apply +, -, *, / as percentages - use this instead of equals -
50 + 20 % is 60, 50 - 10 % is 45, 50 * 30 % is 15, 50 / 75 % is 66.67
'+-'
PLUS_MINUS
swap sign
'PI'
PI
pi - approximately 3.141592653
'RN'
RANDOM
random number - 0 <= x < 1
'SQ', 'SR'
SQR, SQRT
square and square root
'XY'
POWER
power function (x ^ y)
'1X'
INV
inverse (1 / x)
'LG', 'LN'
LOG, LN
logarithm base 10 and natural logarithm
'EX'
EXP
exponential - eⁿ
'DG', 'RD'
DEGREES, RADIANS
use degrees or radians
'SN', 'CS', 'TN'
SIN, COS,
TAN
sine, cosine, tangent
'AS', 'AC', 'AT'
ASIN, ACOS,
ATAN
arcsine, arccosine, arctangent
'BS
UNDO
backspace - delete last digit
'CE'
CLEAR_ERROR
clear error
'CA'
CLEAR
clear all
Other Number Bases
The calculator also works in binary, octal, and hexadecimal.
Digit keys (including the decimal point) that don't apply
to the selected base are disabled.
The current value is converted when you switch.
If the selected base is not decimal, any fractional part is dropped.
Listed below are the additional codes and constants
($.calculator.) for the number base calculator keys.
Code
Constant
Function
'BB'
BASE_2
switch to base 2 (binary)
'BO'
BASE_8
switch to base 8 (octal)
'BD'
BASE_10
switch to base 10 (decimal)
'BH'
BASE_16
switch to base 16 (hexadecimal)
Numeric Precision
Unfortunately, JavaScript has problems with rounding errors during some
calculations (see below). This can be overcome by rounding at a
certain number of digits. However, as this affects all calculated values,
you are able to set the required precision, with a default of 10.
You need to decide on a balance between rounding these obvious
errors and providing sufficient accuracy for your users.
Note that this setting only affects the displayed value and that
the full value is retained in the calculator for further computations.
Examples include:
2.1 * 7 = 14.700000000000001 (OK up to precision 14)
4.225 * 100 = 422.49999999999994 (OK up to precision 12)
162.3 * 100 = 16230.000000000002 (OK up to precision 10)
You can also drive the calculator from the keyboard.
Hold down the Alt key to display the corresponding keystrokes
for each button, where this is different from the text on the button.
Listed below are the keystrokes for the calculator keys.
Keystroke
Calculator Key
Keystroke
Calculator Key
ESC
Close
ENTER
Use
DELETE
Erase
BACKSPACE
BS
HOME
CE
END
CA
0 to 9
0 to 9
a to f
A to F
B, C
Bin, Oct
D, H
Dec, Hex
.
.
+, -
+, -
#
±
*, /
*, /
=
=
%
%
x, r, m
MC, MR, MS
<, >
M+, M-
p
pi
?
rnd
@
x²
!
√
^
x^y
i
1/x
l
log
n
ln
E
eⁿ
s
sin
S
asin
o
cos
O
acos
t
tan
T
atan
G
Deg
R
Rad
Add Your Own Keys
You can add your own keys to the calculator by defining them and
then including their two-character code in the layout.
You should use lower case characters in your code to
avoid conflicting with the standard keys.
For example, you could define increment and decrement keys
that add or subtract one from the current value.
The parameters to the addKeyDef function are
the identifying code, the display label, the type of operation
(binary or unary), the function that implements the action,
any custom CSS styles (prefixed by 'calculator-'),
a constant name for the key for use in layouts, a keyboard equivalent (single character),
and a keystroke name to show when Alt is pressed (up to three characters, optional).
Define your functions separately. They take a single parameter,
being the current instance settings for the calculator.
Update the curValue setting to change the calculation.
Use prevValue for the first value in binary operations.
function increment(inst) {
inst.curValue++;
}
function decrement(inst) {
inst.curValue--;
}
And add CSS styles to apply to your keys (if desired).
Callbacks notify you when certain events occur within the calculator.
Of course, you can still have an onchange
handler for the input field itself.
onOpen is called before a popup calculator opens and allows the
field value to be altered before use. Usually it would be used in conjunction
with an onClose event.
onClose is called when the calculator closes and
provides the (possibly updated) field value, and the calculator instance object.
On close:
$('#closeCalc').calculator({
onClose: function(value, inst) {
alert('Closed with value ' + value);
},
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
Localisations
You can localise the calculator for other languages.
Select a language to change the text and tooltips.
:
You need to load the appropriate language package (see list below), which
adds a language set ($.calculator.regionalOptions[langCode]) and automatically
sets this language as the default for all calculator fields.
You can control the appearance of the calculator via CSS and the
calculatorClass option. The latter is set as a class value
for the calculator instance, allowing it to be individually customised.
The snippet below shows the structure of the calculator along with
the CSS classes you can target for customisation.
The ui-* classes are only present if useThemeRoller is true.
This tab highlights examples of this plugin in use "in the wild".
None as yet.
To add another example, please contact me (wood.keith{at}optusnet.com.au)
and provide the plugin name, the URL of your site, its title,
and a short description of its purpose and where/how the plugin is used.
Quick Reference
A full list of all possible settings is shown below.
Note that not all would apply in all cases. For more detail see the
documentation reference page.
$(selector).calculator({
decimalChar: '.', // Character for the decimal point
buttonText: '...', // Display text for trigger button
buttonStatus: 'Open the calculator', // Status text for trigger button
closeText: 'Close', // Display text for close link
closeStatus: 'Close the calculator', // Status text for close link
useText: 'Use', // Display text for use link
useStatus: 'Use the current value', // Status text for use link
eraseText: 'Erase', // Display text for erase link
eraseStatus: 'Erase the value from the field', // Status text for erase link
backspaceText: 'BS', // Display text for backspace link
backspaceStatus: 'Erase the last digit', // Status text for backspace link
clearErrorText: 'CE', // Display text for clear error link
clearErrorStatus: 'Erase the last number', // Status text for clear error link
clearText: 'CA', // Display text for clear link
clearStatus: 'Reset the calculator', // Status text for clear link
memClearText: 'MC', // Display text for memory clear link
memClearStatus: 'Clear the memory', // Status text for memory clear link
memRecallText: 'MR', // Display text for memory recall link
memRecallStatus: 'Recall the value from memory', // Status text for memory recall link
memStoreText: 'MS', // Display text for memory store link
memStoreStatus: 'Store the value in memory', // Status text for memory store link
memAddText: 'M+', // Display text for memory add link
memAddStatus: 'Add to memory', // Status text for memory add link
memSubtractText: 'M-', // Display text for memory subtract link
memSubtractStatus: 'Subtract from memory', // Status text for memory subtract link
base2Text: 'Bin', // Display text for base 2 link
base2Status: 'Switch to binary', // Status text for base 2 link
base8Text: 'Oct', // Display text for base 8 link
base8Status: 'Switch to octal', // Status text for base 8 link
base10Text: 'Dec', // Display text for base 10 link
base10Status: 'Switch to decimal', // Status text for base 10 link
base16Text: 'Hex', // Display text for base 16 link
base16Status: 'Switch to hexadecimal', // Status text for base 16 link
degreesText: 'Deg', // Display text for degrees link
degreesStatus: 'Switch to degrees', // Status text for degrees link
radiansText: 'Rad', // Display text for radians link
radiansStatus: 'Switch to radians', // Status text for radians link
isRTL: false, // True if right-to-left language, false if left-to-right
showOn: 'focus', // 'focus' for popup on focus, 'button' for trigger button,
// 'both' for either, 'operator' for non-numeric character entered,
// 'opbutton' for operator/button combination
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
isOperator: null, // Call back function to determine if a keystroke opens the calculator
showAnim: 'show', // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
duration: 'normal', // Duration of display/closure
appendText: '', // Display text following the input box, e.g. showing the format
useThemeRoller: false, // True to add ThemeRoller classes
calculatorClass: '', // Additional CSS class for the calculator for an instance
showFormula: false, // True to display formula as it's entered, false to hide it
prompt: '', // Text across the top of the calculator
layout: this.standardLayout, // Layout of keys
value: 0, // The initial value for inline calculators
base: 10, // The numeric base for calculations
precision: 10, // The number of digits of precision to use in rounding for display
memoryAsCookie: false, // True to save memory into cookie, false for memory only
cookieName: 'calculatorMemory', // Name of cookie for memory
cookieExpires: 0, // The time that the memory cookie expires as a Date or number of seconds
cookiePath: '', // The path for the memory cookie
useDegrees: false, // True to use degress for trigonometric functions, false for radians
constrainInput: true, // True to restrict typed characters to numerics, false to allow anything
onOpen: null, // Define a callback function before the panel is opened
onButton: null, // Define a callback function when a button is activated
onClose: null // Define a callback function when the panel is closed
});
$.calculator.regionalOptions[] // Language/country-specific localisations
$.calculator.standardLayout // Standard calculator layout with simple operations
$.calculator.scientificLayout // Extended calculator layout with common scientific operations
$.calculator.setDefaults(settings) // Set global defaults
$.calculator.addKeyDef(code, label, type, func, style,
constant, keystroke, keyName) // Add a key definition
$(selector).calculator('option', settings) // Change instance settings
$(selector).calculator('option', name, value) // Change a single setting
$(selector).calculator('option', name) // Retrieve an instance setting
$(selector).calculator('destroy') // Remove calculator functionality
$(selector).calculator('show') // Show the calculator
$(selector).calculator('hide') // Hide the calculator
$(selector).calculator('enable') // Enable the calculator
$(selector).calculator('disable') // Disable the calculator
$(selector).calculator('isDisabled') // Is the calculator disabled?
Usage
Include the jQuery library (1.7+) in the head section of your page.
Localisation packages are available for download
and should be loaded after the main calculator code. These packages
automatically apply their settings as global default values.