A jQuery plugin that attaches a popup calculator to an input field. If you find this plugin useful please vote for it on the jQuery site.
The current version is 1.3.2 and is available under the GPL and MIT licences. 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.
Default calculator:
$('#defaultCalc').calculator();
$('#removeCalc').toggle(function() {
$(this).text('Re-attach');
$('#defaultCalc').calculator('destroy');
},
function() {
$(this).text('Remove');
$('#defaultCalc').calculator();
}
);
The defaults are:
You can override the defaults globally as shown below:
$.calculator.setDefaults({prompt: 'Calculate it!'});
Processed fields are marked with a class of hasCalculator
and are not re-processed if targetted a second time.
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.
Button only trigger:
$('#buttonCalc').calculator({showOn: 'button'});
$('.buttonDisable').toggle(function() {
$(this).text('Enable').siblings('input').calculator('disable');
}, function() {
$(this).text('Disable').siblings('input').calculator('enable');
});
Image only trigger:
$('#imageCalc').calculator({showOn: 'button',
buttonImageOnly: true, buttonImage: 'img/calculator.png'});
Focus and button trigger:
$('#bothCalc').calculator({showOn: 'both', buttonImage: 'img/calculator.png'});
Operator entry only (any non-numeric):
$('#operatorCalc').calculator({showOn: 'operator'});
Operator entry customised:
$('#operator2Calc').calculator({
showOn: 'operator', isOperator: mathsOnly});
function mathsOnly(ch, event, value, base, decimalChar) {
return '+-*/'.indexOf(ch) > -1 && !(ch == '-' && value == '');
}
Operator entry or button:
$('#opbuttonCalc').calculator({showOn: 'opbutton',
buttonImageOnly: true, buttonImage: 'img/calculator.png'});
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.
Show :
$('#animCalc').calculator({showOn: 'both'});
var anims = ['show', 'fadeIn', 'slideDown', 'blind', 'blind', 'bounce',
'clip','clip', 'drop', 'drop', 'fold', 'fold', 'slide', 'slide', ''];
var animOpts = [null, null, null, {}, {direction: 'horizontal'}, {},
{}, {direction: 'horizontal'}, {}, {direction: 'up'}, {},
{horizFirst: true}, {}, {direction: 'up'}, {}];
$('#duration,#animation').change(function() {
var index = parseInt($('#animation').val(), 10);
$('#animCalc').calculator('change', {showAnim: anims[index],
showOptions: animOpts[index], duration: $('#duration').val()});
});
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').toggle(function() {
$(this).text('Enable');
$('#inlineCalc').calculator('disable');
}, function() {
$(this).text('Disable');
$('#inlineCalc').calculator('enable');
});
Set a value:
$('#inlineSet').click(function() {
$('#inlineCalc').calculator('change',
'value', parseFloat($('#inlineValue').val()));
});
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.
Inverted with memory:
$('#memoryCalc').calculator({layout:
['MC_0_._=_+' + $.calculator.CLOSE, 'MR_1_2_3_-' + $.calculator.USE,
'MS_4_5_6_*' + $.calculator.ERASE, 'M+_7_8_9_/'],
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
Listed below are the standard codes and constants
($.calculator.) for the calculator keys.
| Code | Constant | Function |
|---|---|---|
| ' ' (two spaces) | SPACE |
an empty space |
| '_ ' | HALF_SPACE | half an empty space |
| '@X' | CLOSE | close the calculator |
| '@U' | USE |
copy the value and close the calculator |
| '@E' | ERASE |
erase the field and close the calculator |
| '_0' to '_9' | 0 to 9 |
the decimal digits 0 to 9 |
| '_A' to '_F' | A to F |
the hexadecimal digits A to F |
| '_.' | DECIMAL | the decimal point |
| '_+, '_-' | ADD, SUBTRACT |
addition and subtraction |
| '_*', '_/' | MULTIPLY, DIVIDE |
multiplication and division |
| '_=' | EQUALS | equals - evaluate calculation |
| 'MC' | MEM_CLEAR | memory clear |
| 'MR' | MEM_RECALL | memory recall |
| 'MS' | MEM_STORE | memory store |
| 'M+' | MEM_ADD | memory add |
| 'M-' | MEM_SUBTRACT | memory subtract |
Another layout example - this time with additional scientific functions.
This is a predefined layout: $.calculator.scientificLayout.
Scientific:
$('#scientificCalc').calculator({layout: $.calculator.scientificLayout,
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
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 |
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.
Number base:
$('#baseCalc').calculator({layout: ['BBBOBDBH', '_0_1_2_3_+@X',
'_4_5_6_7_-@U', '_8_9_A_B_*@E', '_C_D_E_F_/', 'BSCECA_._='],
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
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) |
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:
Precision:
$('#precisionCalc').calculator({layout: $.calculator.scientificLayout,
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
$('#precisionSelect').change(function() {
$('#precisionCalc').calculator('change', {precision: $(this).val()});
});
You can save the calculator memory value as a cookie to have it reappear next time.
Memory cookie:
$('#cookieCalc').calculator({memoryAsCookie: true,
layout: $.calculator.scientificLayout,
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png',
onButton: function() {
showCookie();
}});
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.
Keyboard driven:
$('#keyboardCalc').calculator({layout: $.calculator.scientificLayout,
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
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 |
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).
$.calculator.addKeyDef('in', '++', $.calculator.unary,
increment, 'mykey', 'INC', ']');
$.calculator.addKeyDef('de', '--', $.calculator.unary,
decrement, 'mykey', 'DEC', '[');
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).
.calculator-row button.calculator-mykey { background-color: lightblue; }
With increment/decrement:
$('#incDecCalc').calculator({layout: [' _7_8_9_+' + $.calculator.CLOSE,
'in_4_5_6_-' + $.calculator.USE,
'de_1_2_3_*' + $.calculator.ERASE, ' _0_._=_/'],
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
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.
On open:
$('#openCalc').calculator({
onOpen: function(value, inst) {
value = parseFloat(value || 0);
$(this).val((isNaN(value) ? 0 : value) / 100);
},
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
onButton is called for each activated button and
provides the button's label, the current calculator value,
and the calculator instance object.
On button: After the current value is
$('#pressCalc').calculator({
onButton: function(label, value, inst) {
$('#keyLabel').text(label);
$('#current').text(value);
},
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
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'});
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.regional[langCode]) and automatically sets this language as the default for all calculator fields.
<script type="text/javascript" src="jquery.calculator-fr.js"></script>
Thereafter, if desired, you can restore the original language settings.
$.calculator.setDefaults($.calculator.regional['']);
And then configure the language per calculator field.
$('#l10nCalc').calculator($.calculator.regional['fr']);
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.
With background:
$('#withBGCalc').calculator({calculatorClass: 'withBG',
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
.withBG { background: #eee url(img/grey-bg.jpg) no-repeat; }
.withBG .calculator-result { opacity: 0.8; }
.withBG .calculator-row button { background: transparent;
color: #fff; font-weight: bold; }
.withBG .calculator-keystroke { color: #fff; background-color: #727375; }
Midnight big buttons:
$('#midnightCalc').calculator({calculatorClass: 'midnight',
closeText: 'X', useText: 'Y', eraseText: 'N',
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
.calculator-popup.midnight { background: #10085a; }
.midnight .calculator-space { width: 38px; }
.midnight .calculator-result { background-color: #1a0d91;
color: #fff; font-size: 1.5em; }
.midnight .calculator-row .calculator-undo,
.midnight .calculator-row .calculator-clear-error,
.midnight .calculator-row .calculator-clear {
font-size: 1em; padding-left: 3px; }
.midnight .calculator-row button { width: 38px; height: 38px; padding: 5px;
background: url(img/midnight.gif) no-repeat; border: none;
color: #fff; font-size: 1.5em; font-weight: bold; }
.midnight .calculator-row .calculator-key-down { padding: 7px 3px 3px 7px;
background: url(img/midnight.gif) no-repeat -38px 0px; }
.midnight .calculator-keystroke { width: 30px; height: 20px; color: #fff;
background-color: #10085a; font-weight: normal; font-size: 0.8em; }
Alternate native style:
$('#styleCalc').calculator({
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
$('#styleSelect').change(function() {
$('#theme').attr('href', 'css/' + $(this).val());
});
To use ThemeRoller styling instead
set the useThemeRoller option and include your favourite theme CSS.
ThemeRoller styling:
$('#themeRollerCalc').calculator({useThemeRoller: true,
prompt: 'Using ThemeRoller', layout: $.calculator.scientificLayout,
showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});
$('#themeRollerSelect').change(function() {
$('#themeUI').attr('href', 'themes16/' + $(this).val() + '/ui.all.css');
});
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.
<div class="calculator-popup or calculator-inline calculatorClass ui-widget ui-widget-content">
<div class="calculator-prompt ui-widget-header ui-corner-all">...</div>
<div class="calculator-result ui-widget-header"><span>0</span></div>
<div class="calculator-row">
<button class="calculator-ctrl calculator-base
calculator-base10 calculator-base-active ui-state-highlight">Dec
<span class="calculator-keystroke ui-state-error">D</span>
</button>
<button class="calculator-ctrl calculator-angle
calculator-radians calculator-angle-active ui-state-highlight">Rad
<span class="calculator-keystroke ui-state-error">R</span>
</button>
<button class="calculator-oper calculator-memory
calculator-mem-recall calculator-mem-empty ui-state-default">MR
<span class="calculator-keystroke ui-state-error">r</span>
</button>
</div>
<div class="calculator-row">
<button class="calculator-digit ui-state-default">1</button>
<button class="calculator-digit ui-state-default">2</button>
<button class="calculator-digit ui-state-default">3</button>
<span class="calculator-space"></span>
<button class="calculator-oper calculator-arith calculator-add ui-state-default">+</button>
<button class="calculator-ctrl calculator-close ui-state-highlight">Close
<span class="calculator-keystroke calculator-keyname ui-state-error">Esc</span>
</button>
</div>
<div class="calculator-row">...</div>
...
<div style="clear: both;"/>
</div>
This tab highlights examples of this plugin in use "in the wild".
None as yet.
To add another example, please contact me (kbwood{at}iinet.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.
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
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.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('change', settings) // Change instance settings
$(selector).calculator('change', name, value)
$(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?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><style type="text/css">@import "jquery.calculator.css";</style>
<script type="text/javascript" src="jquery.calculator.js"></script>
Alternately, you can use the packed version jquery.calculator.pack.js (20.3K vs 52.1K),
or the minified version jquery.calculator.min.js (26.8K, 8.2K when zipped).$(selector).calculator();
You can include custom settings as part of this process.
$(selector).calculator({showOn: 'button'});For more detail see the documentation reference page. Or see a minimal page that you could use as a basis for your own investigations.
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.
Other translations are welcomed.
Great work on the calculator!
I've been using your calculator plugin in my MVC app and it works perfect.
Thank you for your work on the JQuery Calculator. It's great!
I downloaded your jQuery calculator last night and put it on our web site. I think that it is great and will be very useful.
Contact Keith Wood at kbwood{at}iinet.com.au with comments or suggestions.
| Version | Date | Changes |
|---|---|---|
| 1.3.2 | 09 Apr 2011 |
|
| 1.3.1 | 18 Dec 2010 |
|
| 1.3.0 | 04 Sep 2010 |
|
| 1.2.5 | 10 Jul 2010 |
|
| 1.2.4 | 08 May 2010 |
|
| 1.2.3 | 17 Oct 2009 |
|
| 1.2.2 | 12 Sep 2009 |
|
| 1.2.1 | 13 Jun 2009 |
|
| 1.2.0 | 21 Mar 2009 |
|
| 1.1.1 | 31 Jan 2009 |
|
| 1.1.0 | 27 Dec 2008 |
|
| 1.0.2 | 29 Nov 2008 |
|
| 1.0.1 | 08 Nov 2008 |
|
| 1.0.0 | 18 Oct 2008 |
|