Default Settings

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:  


$('#removeCalc').click(function() {
	var destroy = $(this).text() === 'Remove';
	$(this).text(destroy ? 'Re-attach' : 'Remove');
	$('#defaultCalc').calculator(destroy ? 'destroy' : {});

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 is-calculator and are not re-processed if targeted 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').click(function() {
	var disable = $(this).text() === 'Disable';
	$(this).text(disable ? 'Enable' : 'Disable');
	$(this).siblings('input').calculator(disable ? 'disable' : '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:  

	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('option', {showAnim: anims[index],
		showOptions: animOpts[index], duration: $('#duration').val()});
Inline Calculator

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');

Set a value:  

$('#inlineSet').click(function() {
		'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.

Set the showFormula option to display the formula being evaluated.

Show formula:

Inverted with memory:

$('#showFormula').change(function() {
	$('#memoryCalc').calculator('option', {showFormula: $(this).is(':checked')});
	['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.

'  ' (two spaces)SPACE an empty space
'_ 'HALF_SPACEhalf an empty space
'@X'CLOSEclose 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
'_.'DECIMALthe decimal point
'_+, '_-'ADD, SUBTRACT addition and subtraction
'_*', '_/'MULTIPLY, DIVIDE multiplication and division
'_='EQUALSequals - evaluate calculation
'MC'MEM_CLEARmemory clear
'MR'MEM_RECALLmemory recall
'MS'MEM_STOREmemory store
'M+'MEM_ADD memory add
'M-'MEM_SUBTRACT memory subtract
Scientific Layout

Another layout example - this time with additional scientific functions. This is a predefined layout: $.calculator.scientificLayout.


$('#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.

'_%'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_MINUSswap sign
'PI'PIpi - approximately 3.141592653
'RN'RANDOMrandom number - 0 <= x < 1
'SQ', 'SR'SQR, SQRT square and square root
'XY'POWERpower function (x ^ y)
'1X'INVinverse (1 / x)
'LG', 'LN'LOG, LN logarithm base 10 and natural logarithm
'EX'EXPexponential - eⁿ
'DG', 'RD'DEGREES, RADIANS use degrees or radians
'SN', 'CS', 'TN'SIN, COS, TANsine, cosine, tangent
'AS', 'AC', 'AT'ASIN, ACOS, ATANarcsine, arccosine, arctangent
'BSUNDObackspace - delete last digit
'CE'CLEAR_ERRORclear error
'CA'CLEARclear 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.

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.

'BB'BASE_2switch to base 2 (binary)
'BO'BASE_8switch to base 8 (octal)
'BD'BASE_10switch to base 10 (decimal)
'BH'BASE_16switch 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:


$('#precisionCalc').calculator({layout: $.calculator.scientificLayout,
	showOn: 'both', buttonImageOnly: true, buttonImage: 'img/calculator.png'});

$('#precisionSelect').change(function() {
	$('#precisionCalc').calculator('option', {precision: $(this).val()});
Memory Cookie

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() {
Keystroke Equivalents

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.

KeystrokeCalculator KeyKeystrokeCalculator Key
0 to 90 to 9a to fA to F
B, CBin, OctD, HDec, Hex
..+, -+, -
#±*, /*, /
x, r, mMC, MR, MS<, >M+, M-
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).

$.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) {

function decrement(inst) {

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'});
Callback Functions

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:

	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

	onButton: function(label, value, inst) {
	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:

	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.regionalOptions[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.


And then configure the language per calculator field.

Styling the Calculator

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:


    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', buttonImage: 'img/calculator.png'});
$('#themeRollerSelect').change(function() {
	$('#themeUI').attr('href', 'themesDemo/' + $(this).val() + '/jquery-ui.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 class="calculator-ctrl calculator-angle
			calculator-radians calculator-angle-active ui-state-highlight">Rad
			<span class="calculator-keystroke ui-state-error">R</span>
		<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>
	<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>
	<div class="calculator-row">...</div>
	<div style="clear: both;"/>
In the Wild

This tab highlights examples of this plugin in use "in the wild".

To add another example, please contact me (wood.keith{at} 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.

	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?