autoNumeric is a standalone library that provides live as-you-type formatting for international numbers and currencies.

Overview

autonumeric.org

Latest Version Build Status Known Vulnerabilities Coverage Status
Gitter chat Npm downloads per month jsDelivr downloads per month

AutoNumeric npm info

What is autoNumeric?

autoNumeric is a standalone Javascript library that provides live as-you-type formatting for international numbers and currencies.

The latest stable branch is always on master. Currently this is version 4.2.*.
If you want to try the new features, you can check out the latest development version in the next branch.
That next branch can see changes in the API (check the semver), but is always fully tested for regressions.

For older stable versions, please take a look here.
Alternatively, you can use our guide for upgrading from version 1.9/2 to version 4.

Finally, you can check what could be the next features coming to autoNumeric on the projects page (feel free to participate!).

Highlights

autoNumeric main features are :

  • Easy to use and configure
// Initialization
new AutoNumeric('.myInput', { currencySymbol : '$' });
  • Very high configurability (more than 40 options available)
// The options are...optional :)
const autoNumericOptionsEuro = {
    digitGroupSeparator        : '.',
    decimalCharacter           : ',',
    decimalCharacterAlternative: '.',
    currencySymbol             : '\u202f€',
    currencySymbolPlacement    : AutoNumeric.options.currencySymbolPlacement.suffix,
    roundingMethod             : AutoNumeric.options.roundingMethod.halfUpSymmetric,
};

// Initialization
new AutoNumeric(domElement, autoNumericOptionsEuro);
  • User experience oriented ; using autoNumeric just feels right and natural, specially with the function chaining feature
anElement.french()
         .set(42)
         .update({ options })
         .formSubmitJsonNumericString(callback)
         .clear();
  • Supports most international numeric formats and currencies
    (If the one you use is not supported yet, open an issue and we'll add it as soon as possible!)
  • The mobile Android Chrome browser is partially supported

And also:

  • Any number of different formats can be used at the same time on the same page.
    Each input can be configured by either setting the options as HTML5 data attributes, or directly passed as an argument in the Javascript code
  • The settings can easily be changed at any time using the update method or via a callback
  • autoNumeric supports input elements as well as most text elements with the contenteditable attribute, allowing you to place formatted numbers and currencies on just about any part of your pages
  • AutoNumeric elements can be linked together allowing you to perform one action on multiple elements at once
  • 8 pre-defined currency options as well as 33 common options allows you to directly use autoNumeric by skipping the option configuration step
  • 26 built-in methods gives you the flexibility needed to use autoNumeric to its full potential
  • 22 global methods that allows to control sets of AutoNumeric-managed elements at once
  • 21 additional methods specialized for managing form management and submission
  • A formula mode that allows to quickly enter and evaluate math expressions inside the element
  • 17 static functions provided by the AutoNumeric class
  • And more than 40 options allowing you to precisely customize your currency format and behavior

With that said, autoNumeric supports most international numeric formats and currencies including those used in Europe, Asia, and North and South America.


Table of contents

Getting started

Installation

You can install autoNumeric with your preferred dependency manager:

# with `yarn` :
yarn add autonumeric
# or with `npm` :
npm install autonumeric --save

How to use?

In the browser

Simply include autoNumeric in your html <header> tag.
No other files or libraries are required ; autoNumeric has no dependency.

<script src="autoNumeric.min.js" type="text/javascript"></script>
<!-- ...or, you may also directly use a CDN :-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<!-- ...or -->
<script src="https://unpkg.com/autonumeric"></script>

In another script

If you want to use AutoNumeric in your code, you can import the src/AutoNumeric.js file as an ES6 module using:

import AutoNumeric from 'autonumeric';

Then you can initialize autoNumeric with or without options :

// autoNumeric with the defaults options
anElement = new AutoNumeric(domElement);

// autoNumeric with specific options being passed
anElement = new AutoNumeric(domElement, { options });

// autoNumeric with a css selector and a pre-defined language options
anElement = new AutoNumeric('.myCssClass > input').french();

(See the available language list here)

You're done!

Note : an AutoNumeric object can be initialized in various ways, check those out here

In Web Workers

Some static AutoNumeric functions that do not access nor modify the DOM can be used in Web Workers (ie. AutoNumeric.format(), AutoNumeric.unformat(), etc.).
In order to be able to use AutoNumeric in those web workers, you need to import the source file src/main.js, not the generated one found in dist/AutoNumeric.js. For instance, by importing the library like that:

import AutoNumeric from '../node_modules/autonumeric/src/main';

Doing this will allow your project Webpack configuration to compile it correctly (and use tree shaking as needed).

On which elements can it be used?

autoNumeric can be used in two ways ;

  • with event listeners when used on <input> elements or on contenteditable-enabled elements making them reactive (in a read/write mode), or
  • without event listeners when used on DOM elements not having the contenteditable attribute set to true, essentially acting as a format-once-and-forget-read only mode.

On <input> elements

When used on an <input> element, you'll be able to interact with its value and get a formatted input value as-you-type, using the full power of autoNumeric.

Please note than due to browser constraints, only the following supported <input> types are supported :

  • text,
  • tel,
  • hidden, or
  • no type specified at all
<input type='text' value="1234.56">
<input type='tel' value="1234.56">
<input type='hidden' value="1234.56">
<input value="1234.56">

Note : the number type is not supported simply because autoNumeric formats numbers as strings (ie. '123.456.789,00 &#8364;') that this input type does not allow.

On contenteditable-enabled elements

Any element in the following allowedTagList that support the contenteditable attribute can be initialized by autoNumeric. This means that anywhere on a page, on any DOM element, you can harness the power of autoNumeric which will allow you to mask the user inputs.

Given the following html code...:

<p id="editableDom" contenteditable="true">12345678.9012</p>

you can initialize this <p> element with autoNumeric:

new AutoNumeric('#editableDom').french();

...and it will act exactly like an <input> element controlled by autoNumeric.

On other DOM elements

You can use autoNumeric to format a DOM element value once on load.
This means it will then not react to any user interaction.

The following elements are accepted :

const allowedTagList = [
    'b', 'caption', 'cite', 'code', 'const', 'dd', 'del', 'div', 'dfn', 'dt', 'em', 'h1', 'h2', 'h3',
    'h4', 'h5', 'h6', 'ins', 'kdb', 'label', 'li', 'option', 'output', 'p', 'q', 's', 'sample',
    'span', 'strong', 'td', 'th', 'u'
]

Tips:
Since the number type is not supported, if you want to display a numeric keyboard when selecting an AutoNumeric-managed element in a mobile browser, you can use the input tel type.

In the future, you'll be able to add the inputmode="numeric" Html attribute in order to achieve the same effect.

Initialization

An AutoNumeric object can be initialized in various ways.

Initialize one AutoNumeric object

It always takes either a DOM element reference as its first argument, or a css string selector.
Note: only one element can be selected this way, since under the hood document.querySelector is called, and this only return one element.
If you need to be able to select and initialize multiple elements in one call, then consider using the static AutoNumeric.multiple() function

anElement = new AutoNumeric(domElement); // With the default options
anElement = new AutoNumeric(domElement, { options }); // With one option object
anElement = new AutoNumeric(domElement, 'euroPos'); // With a named pre-defined string
anElement = new AutoNumeric(domElement, [{ options1 }, 'euroPos', { options2 }]); // With multiple option objects (the latest option overwriting the previous ones)
anElement = new AutoNumeric(domElement).french(); // With one pre-defined language object
anElement = new AutoNumeric(domElement).french({ options });// With one pre-defined language object and additional options that will override those defaults

// ...or init and set the value in one call :
anElement = new AutoNumeric(domElement, 12345.789); // With the default options, and an initial value
anElement = new AutoNumeric(domElement, 12345.789, { options });
anElement = new AutoNumeric(domElement, '12345.789', { options });
anElement = new AutoNumeric(domElement, 12345.789, 'euroPos');
anElement = new AutoNumeric(domElement, 12345.789, [{ options1 }, 'euroPos', { options2 }]);
anElement = new AutoNumeric(domElement, null, { options }); // With a null initial value
anElement = new AutoNumeric(domElement, 12345.789).french({ options });
anElement = new AutoNumeric(domElement, 12345.789, { options }).french({ options }); // Not really helpful, but possible

// The AutoNumeric constructor class can also accept a string as a css selector. Under the hood this use `QuerySelector` and limit itself to only the first element it finds.
anElement = new AutoNumeric('.myCssClass > input');
anElement = new AutoNumeric('.myCssClass > input', { options });
anElement = new AutoNumeric('.myCssClass > input', 'euroPos');
anElement = new AutoNumeric('.myCssClass > input', [{ options1 }, 'euroPos', { options2 }]);
anElement = new AutoNumeric('.myCssClass > input', 12345.789);
anElement = new AutoNumeric('.myCssClass > input', 12345.789, { options });
anElement = new AutoNumeric('.myCssClass > input', 12345.789, 'euroPos');
anElement = new AutoNumeric('.myCssClass > input', 12345.789, [{ options1 }, 'euroPos', { options2 }]);
anElement = new AutoNumeric('.myCssClass > input', null, { options }); // With a null initial value
anElement = new AutoNumeric('.myCssClass > input', 12345.789).french({ options });

Note: AutoNumeric also accepts a limited tag list that it will format on page load, but without adding any event listeners if their contenteditable attribute is not set to true

Initialize multiple AutoNumeric objects at once

If you know you want to initialize multiple elements in one call, you must then use the static AutoNumeric.multiple() function:

// Init multiple DOM elements in one call (and possibly pass multiple values that will be mapped to each DOM element)
[anElement1, anElement2, anElement3] = AutoNumeric.multiple([domElement1, domElement2, domElement3], { options });
[anElement1, anElement2, anElement3] = AutoNumeric.multiple([domElement1, domElement2, domElement3], 'euroPos');
[anElement1, anElement2, anElement3] = AutoNumeric.multiple([domElement1, domElement2, domElement3], [{ options }, 'euroPos']);
[anElement1, anElement2, anElement3] = AutoNumeric.multiple([domElement1, domElement2, domElement3], 12345.789, { options });
[anElement1, anElement2, anElement3] = AutoNumeric.multiple([domElement1, domElement2, domElement3], 12345.789, [{ options }, 'euroPos']);
[anElement1, anElement2, anElement3] = AutoNumeric.multiple.french([domElement1, domElement2, domElement3], [12345.789, 234.78, null], { options });
[anElement1, anElement2, anElement3] = AutoNumeric.multiple.french([domElement1, domElement2, domElement3], [12345.789, 234.78, null], [{ options }, 'euroPos']);

// Special case, if a <form> element is passed (or any other 'parent' (or 'root') DOM element), then autoNumeric will initialize each child `<input>` elements recursively, ignoring those referenced in the `exclude` attribute
[anElement1, anElement2] = AutoNumeric.multiple({ rootElement: formElement }, { options });
[anElement1, anElement2] = AutoNumeric.multiple({ rootElement: formElement, exclude : [hiddenElement, tokenElement] }, { options });
[anElement1, anElement2] = AutoNumeric.multiple({ rootElement: formElement, exclude : [hiddenElement, tokenElement] }, [12345.789, null], { options });

// If you want to select multiple elements via a css selector, then you must use the `multiple` function. Under the hood `QuerySelectorAll` is used.
[anElement1, anElement2] = AutoNumeric.multiple('.myCssClass > input', { options }); // This always return an Array, even if there is only one element selected
[anElement1, anElement2] = AutoNumeric.multiple('.myCssClass > input', [null, 12345.789], { options }); // Idem above, but with passing the initial values too

Note: Using an array of option objects / pre-defined names will always merge those settings. The resulting setting objet will then be applied to all the selected elements ; they will share the exact same settings.

Options

Multiple options allow you to customize precisely how a form input will format your key strokes as you type.
You can check what are the predefined choices for each option as well as a more detailed explanation of how they work on the official documentation page.
You can also generate your custom options object and try those live with the AutoNumeric configurator.

Option Description Default Value
allowDecimalPadding Allow padding the decimal places with zeros. If set to 'floats', padding is only done when there are some decimals. true
alwaysAllowDecimalCharacter Defines if the decimal character or decimal character alternative should be accepted when there is already a decimal character shown in the element. false
caretPositionOnFocus Determine where should be positioned the caret on focus null
createLocalList Determine if a local list of AutoNumeric objects must be kept when initializing the elements and others true
currencySymbol Defines the currency symbol to display ''
currencySymbolPlacement Placement of the currency sign, relative to the number shown (as a prefix or a suffix) 'p'
decimalCharacter Decimal separator character '.'
decimalCharacterAlternative Allow to declare an alternative decimal separator which is automatically replaced by the real decimal character when entered (This is useful in countries where the keyboard numeric pad has a period as the decimal character) null
decimalPlaces Defines the default number of decimal places to show on the formatted value, and to keep as the precision for the rawValue. This can be overridden by the other decimalPlaces* options. 2
decimalPlacesRawValue Defines how many decimal places should be kept for the raw value. This is the precision for float values. null
decimalPlacesShownOnBlur The number of decimal places to show when unfocused null
decimalPlacesShownOnFocus The number of decimal places to show when focused null
defaultValueOverride Helper option for the ASP.NET-specific postback issue null
digitalGroupSpacing Digital grouping for the thousand separator '3'
digitGroupSeparator Thousand separator character ','
divisorWhenUnfocused Defines the number that will divide the current value shown when unfocused null
emptyInputBehavior Defines what to display when the input value is empty (possible options are null, focus, press, always, min, max, zero, number, or a string representing a number) 'focus'
eventBubbles Defines if the custom and native events triggered by AutoNumeric should bubble up or not true
eventIsCancelable Defines if the custom and native events triggered by AutoNumeric should be cancelable true
failOnUnknownOption This option is the 'strict mode' (aka 'debug' mode), which allows autoNumeric to strictly analyse the options passed, and fails if an unknown options is used in the options object. false
formatOnPageLoad Determine if the default value will be formatted on initialization true
formulaMode Defines if the formula mode can be activated by the user false
historySize Determine how many undo states an AutoNumeric object should keep in memory 20
isCancellable Determine if the user can 'cancel' the last modifications done to the element value when using the Escape key true
leadingZero Controls the leading zero behavior (possible options are allow, deny and keep) 'deny'
maximumValue The maximum value that can be entered (10 trillions by default) '10000000000000'
minimumValue The minimum value that can be entered (-10 trillions by default) '-10000000000000'
modifyValueOnWheel Determine if the element value can be incremented / decremented with the mouse wheel. The wheel behavior is modified with the wheelStep option. true
negativeBracketsTypeOnBlur Adds brackets [], parenthesis (), curly braces {}, chevrons <>, angle brackets 〈〉, Japanese quotation marks 「」, half brackets ⸤⸥, white square brackets ⟦⟧, quotation marks ‹› or guillemets «» on negative values when unfocused. The value must be formatted like '<leftBracket>,<rightBracket>'. null
negativePositiveSignPlacement Placement of negative/positive sign relative to the currency symbol (possible options are l (left), r (right), p (prefix) and s (suffix)) null
negativeSignCharacter Defines the negative sign character to use '-'
noEventListeners Defines if the element should have event listeners activated on it.
Note: Setting this to true will prevent any format to be applied once the user starts modifying the element value. This is unlikely what you want.
false
onInvalidPaste Manage how autoNumeric react when the user tries to paste an invalid number (possible options are error, ignore, clamp, truncate or replace) 'error'
outputFormat Defines the localized output format of the getLocalized, form*, formArray* and formJson* methods null
overrideMinMaxLimits Override minimum and maximum limits (possible options are ceiling, floor, ignore and invalid) null
positiveSignCharacter Defines the positive sign character to use (Note: It's only shown if showPositiveSign is set to true) '+'
rawValueDivisor Define the number that will divide the formatted value into the raw value (ie. when displaying '1.23%', the raw value kept is 0.0123 if rawValueDivisor is set to 100) null
readOnly Defines if the element (<input> or another allowed html tag) should be set as read-only on initialization false
roundingMethod Method used for rounding. The possible options are:
S (Round-Half-Up Symmetric (default)),
A (Round-Half-Up Asymmetric),
s (Round-Half-Down Symmetric (lower case s)),
a (Round-Half-Down Asymmetric (lower case a)),
B (Round-Half-Even 'Bankers Rounding'),
U (Round Up 'Round-Away-From-Zero'),
D (Round Down 'Round-Toward-Zero' - same as truncate),
C (Round to Ceiling 'Toward Positive Infinity'),
F (Round to Floor 'Toward Negative Infinity'),
N05 (Rounds to the nearest .05 (same as 'CHF' used in v1.9.* and still valid)),
U05 (Rounds up to next .05),
D05 (Rounds down to next .05)
'S'
saveValueToSessionStorage Allow the decimalPlacesShownOnFocus value to be saved into session storage false
selectNumberOnly Determine if the 'Select All' keyboard command will select the complete input text content (including the currency symbol and suffix text), or only the input numeric value false
selectOnFocus Defines if the element value should be selected on focus. That selection is dependant on the selectNumberOnly option value. true
serializeSpaces Defines how the serialize functions should treat spaces when serializing (convert them to '%20' or '+') '+'
showOnlyNumbersOnFocus Remove the thousand separator, currency symbol and suffix on focus false
showPositiveSign Allow the positive sign symbol + to be displayed for positive numbers false
showWarnings Defines if warnings should be shown. This is safe to disable in production. true
styleRules Defines the rules that calculate the CSS class(es) to apply on the element, based on the raw unformatted value.
This can also be used to call callbacks whenever the rawValue is updated.
null
suffixText Additional text suffix that is added after the number ''
symbolWhenUnfocused Symbol placed as a suffix when unfocused. This is used in combination with the divisorWhenUnfocused option. null
unformatOnHover Defines if the element value should be unformatted when the user hover his mouse over it while holding the Alt key true
unformatOnSubmit Removes formatting on submit event false
valuesToStrings Provide a way for automatically and transparently replacing the formatted value with a pre-defined string, when the raw value is equal to a specific value.
For instance when using { 0: '-' }, the hyphen '-' is displayed when the rawValue is equal to 0. Multiple 'replacements' can be defined.
null
watchExternalChanges Defines if the AutoNumeric element should watch (and format) external changes made without using .set(). This is set to false by default to prevent infinite loops when used with third party frameworks that relies on the 'autoNumeric:rawValueModified' events being sent. false
wheelOn Used in conjonction with the modifyValueOnWheel option, defines when the wheel event will increment or decrement the element value, either when the element is focused, or hovered 'focus'
wheelStep Used in conjonction with the modifyValueOnWheel option, this allow to either define a fixed step (ie. 1000), or a progressive one that is calculated based on the size of the current value 'progressive'

Predefined options

Sometimes you do not want to have to configure every single aspect of your format, specially if it's a common one.
Hence, we provide multiple default options for the most common currencies and number formats.

Predefined language options

autoNumeric provides predefined language options to format currencies.
You can set the pre-defined language option like so:

// Use the methods
new AutoNumeric('.mySelector > input').french();
// ...or just create the AutoNumeric object with the language option
new AutoNumeric('.mySelector > input', AutoNumeric.getPredefinedOptions().French);

Currently, the predefined language options are:

Option name
🇫🇷 French
🇪🇸 Spanish
🇺🇸 NorthAmerican
🇬🇧 British
🇨🇭 Swiss
🇯🇵 Japanese
🇨🇳 Chinese
🇧🇷 Brazilian
🇹🇷 Turkish

If you feel a common currency option is missing, please create a pull request and we'll add it!

Predefined common options

Moreover, autoNumeric provides the following common options:

Option name Description Examples
dotDecimalCharCommaSeparator Set the decimal character as a dot . and the group separator as a comma , 1,234.56
commaDecimalCharDotSeparator Set the decimal character as a comma , and the group separator as a dot . 1.234,56
integer Set the minimum and maximum value so that only an integer can be entered, without any decimal places available 42, -42
integerPos Set the minimum and maximum value so that only a positive integer can be entered 42
integerNeg Set the minimum and maximum value so that only a negative integer can be entered -42
float Set the minimum and maximum value so that a float can be entered, without the default 2 decimal places 1.234, -1.234
floatPos Set the minimum and maximum value so that only a positive float can be entered 1.234
floatNeg Set the minimum and maximum value so that only a negative float can be entered -1.234
numeric Format the value as a numeric string (with no digit group separator, and a dot for the decimal point) 1234.56
numericPos Idem above, but only allow positive values 1234.56
numericNeg Idem above, but only allow negative values -1234.56
euro Same configuration than French 1.234,56 €
euroF Same configuration than euro, with the formula mode activated 1.234,56 €
euroPos Idem above, but only allow positive values 1.234,56 €
euroNeg Idem above, but only allow negative values -1.234,56 €
euroSpace Same configuration than French except a space is used for the group separator instead of the dot 1 234,56 €
euroSpacePos Idem above, but only allow positive values 1 234,56 €
euroSpaceNeg Idem above, but only allow negative values -1 234,56 €
dollar Same configuration than NorthAmerican $1,234.56
dollarF Same configuration than dollar, with the formula mode activated $1,234.56
dollarPos Idem above, but only allow positive values $1,234.56
dollarNeg Idem above, but only allow negative values -$1,234.56
percentageEU2dec Same configuration than French, but display a percent % sign instead of the currency sign, with 2 decimal places 12,34 %
percentageEU2decPos Idem above, but only allow positive values 12,34 %
percentageEU2decNeg Idem above, but only allow negative values -12,34 %
percentageEU3dec Same configuration than French, but display a percent % sign instead of the currency sign, with 3 decimal places 12,345 %
percentageEU3decPos Idem above, but only allow positive values 12,345 %
percentageEU3decNeg Idem above, but only allow negative values -12,345 %
percentageUS2dec Same configuration than NorthAmerican, but display a percent % sign instead of the currency sign, with 2 decimal places 12.34%
percentageUS2decPos Idem above, but only allow positive values 12.34%
percentageUS2decNeg Idem above, but only allow negative values -12.34%
percentageUS3dec Same configuration than NorthAmerican, but display a percent % sign instead of the currency sign, with 3 decimal places 12.345%
percentageUS3decPos Idem above, but only allow positive values 12.345%
percentageUS3decNeg Idem above, but only allow negative values -12.345%

You can set those pre-defined options like so:

new AutoNumeric('.mySelector > input', AutoNumeric.getPredefinedOptions().integerPos);
Predefined style rules

With the styleRules option, you can define the rules that add or remove the CSS class(es) from the element, based on the raw unformatted value.
This option can also be used to define custom callbacks in the userDefined attribute, that will be called whenever the rawValue is updated.

Predefined styles are available so you do not have to create them:

Positive and negative

Sets the 'autoNumeric-positive' css class whenever the raw value is positive.
Sets the 'autoNumeric-negative' css class whenever the raw value is negative.

new AutoNumeric(domElement, { styleRules: AutoNumeric.options.styleRules.positiveNegative });
Range from 0 to 100, in 4 steps

Sets the 'autoNumeric-red' css class whenever the raw value is between 0 and 25 excluded.
Sets the 'autoNumeric-orange' css class whenever the raw value is between 25 and 50 excluded.
Sets the 'autoNumeric-yellow' css class whenever the raw value is between 50 and 75 excluded.
Sets the 'autoNumeric-green' css class whenever the raw value is between 75 and 100 excluded.

new AutoNumeric(domElement, { styleRules: AutoNumeric.options.styleRules.range0To100With4Steps });
Odd and even

Sets the 'autoNumeric-even' css class whenever the raw value is even.
Sets the 'autoNumeric-odd' css class whenever the raw value is odd.

new AutoNumeric(domElement, { styleRules: AutoNumeric.options.styleRules.evenOdd });
Small range around zero, from -1 to 1

Sets the 'autoNumeric-small-negative' css class whenever the raw value is between -1 and 0 excluded.
Sets the 'autoNumeric-zero' css class whenever the raw value is equal to 0.
Sets the 'autoNumeric-small-positive' css class whenever the raw value is between 0 excluded and 1.

new AutoNumeric(domElement, { styleRules: AutoNumeric.options.styleRules.rangeSmallAndZero });
Custom callbacks

Custom callbacks can be defined and will be called every time the raw value is updated.
You can add as many callbacks you want in the userDefined attribute of the styleRules object in the options.
Each userDefined array entry should at least provide a function as the callback attribute.
This callback function is passed the rawValue as the single parameter (except if classes is null or undefined, see below).

Depending of what type of data the callback function returns, and what the content of the classes attribute is, it will either uses CSS class names defined in the classes attribute, or just call the callback with the current AutoNumeric object passed as a parameter if classes is null or undefined.

# Callback return type classes content Result
1 a boolean a single String If true, add the single class defined in classes. If false removes it.
2 a boolean an Array with 2 values (array indexes) If true, add the first element of the array, otherwise the second
3 an integer an Array with multiple values (array indexes) Will add the selected CSS class classes[index], and remove the others
4 an Array of integer an Array with multiple values (array indexes) Will add all the given selected CSS classes, and remove the others
5 null or undefined There, the callback have access to the current AutoNumeric object passed as its argument, which means you are free to do whatever you want from here!

See the following examples:

const options = {
    styleRules : {
        userDefined: [
            // 1) If 'classes' is a string, set it if `true`, remove it if `false`
            { callback: rawValue => { return true; }, classes: 'thisIsTrue' },
            // 2) If 'classes' is an array with only 2 elements, set the first class if `true`, the second if `false`
            { callback: rawValue => rawValue % 2 === 0, classes: ['autoNumeric-even', 'autoNumeric-odd'] },
            // 3) Return only one index to use on the `classes` array (here, 'class3')
            { callback: rawValue => { return 2; }, classes: ['class1', 'class2', 'class3'] },
            // 4) Return an array of indexes to use on the `classes` array (here, 'class1' and 'class3')
            { callback: rawValue => { return [0, 2]; }, classes: ['class1', 'class2', 'class3'] },
            // 5) If 'classes' is `undefined` or `null`, then the callback is called with the AutoNumeric object passed as a parameter
            { callback: anElement => { return anElement.getFormatted(); } },
        ],
    },
}

Special options

noEventListeners

Using the noEventListeners option allow autoNumeric to only format without adding any event listeners to an input, or any other DOM elements (that the function would accept as a parameter). This would be useful for read-only values for instance.

// Initialize without setting up any event listeners
anElement = new AutoNumeric(domElement, 12345.789, { options }).remove(); // This is the default existing way of doing that...
// ...but you can also directly pass a special option `noEventListeners` to prevent the initial creation of those event listeners
anElement = new AutoNumeric(domElement, 12345.789, { noEventListeners: true });

In the latter case, it initialize the AutoNumeric element, except it does not add any event listeners. Which means it format the value only once and then let the user modify it freely.
Note: The value can then be formatted via a call to set.

readOnly

AutoNumeric can initialize an <input> element with the readonly property by setting the readOnly option to true in the settings:

anElement = new AutoNumeric(domElement, 12345.789, { readOnly: true });

For more detail on how to use each options, please take a look at the detailed comments in the source code for the defaultSettings object.

Options update

Options can be added and/or modified after the initialization has been done.

Either by passing an option object that contains multiple options,

anElement.update({ moreOptions });
anElement.update(AutoNumeric.getPredefinedOptions().NorthAmerican); // Update the settings (and immediately reformat the element accordingly)

by passing multiple option objects, the latter overwriting the settings from the former ones...

anElement.update({ moreOptions1 }, { moreOptions2 }, 'euro');
// or in a single array
anElement.update([{ moreOptions1 }, { moreOptions2 }, 'euro']);

...or by changing the options one by one (or by calling a pre-defined option object).

anElement.options.minimumValue('12343567.89');
anElement.options.allowDecimalPadding(false);

At any point, you can reset the options by calling the options.reset() method. This effectively drop any previous options you could have set, then load back the default settings.

anElement.options.reset();

Lastly, the option object can be accessed directly, thus allowing to query each options globally too

anElement.getSettings(); // Return the options object containing all the current autoNumeric settings in effect

Methods

autoNumeric provides numerous methods to access and modify the element value, formatted or unformatted, at any point in time.
It does so by providing access to those methods via the AutoNumeric object class (declared as an ES6 Module).

First. you need to get a reference to the AutoNumeric module that you need to import:

import AutoNumeric from 'autonumeric';

Then you'll be able to access either the methods on the instantiated AutoNumeric object, or the static functions directly by using the AutoNumeric class.

Instantiated methods

Set, get, format, unformat and other usual AutoNumeric functions

The following functions are available on all autoNumeric-managed elements:

Method Description Call example
set Set the value (that will be formatted immediately) anElement.set(42.76);
set Set the value and update the setting in one go anElement.set(42.76, { options });
set Set the value, but do not save the new state in the history table (used for undo/redo actions) anElement.set(42.76, { options }, false);
setUnformatted Set the value (that will not be formatted immediately) anElement.setUnformatted(42.76);
setUnformatted Set the value and update the setting in one go (the value will not be formatted immediately) anElement.setUnformatted(42.76, { options });
getNumericString Return the unformatted number as a string anElement.getNumericString();
get Alias for the .getNumericString() method (this is deprecated and will be removed soon™) anElement.get();
getFormatted Return the formatted string anElement.getFormatted();
getNumber Return the unformatted number as a number (Warning: If you are manipulating a number bigger than Number.MAX_SAFE_INTEGER, you will encounter problems if you try to retrieve it as a number and not a string) anElement.getNumber();
getLocalized Return the localized unformatted number as a string anElement.getLocalized();
getLocalized Return the localized unformatted number as a string, using the outputFormat option override passed as a parameter anElement.getLocalized(forcedOutputFormat);
getLocalized Idem above, but with a callback function and a forced outputFormat anElement.getLocalized(forcedOutputFormat, callback);
getLocalized Idem above, but with a callback function anElement.getLocalized(callback);
get* Pass the result of the get* function to the given callback, see here anElement.get*(funcCallback);
reformat Force the element to reformat its value again (in case the formatting has been lost) anElement.reformat();
unformat Remove the formatting and keep only the raw unformatted value in the element (as a numeric string) anElement.unformat();
unformatLocalized Remove the formatting and keep only the localized unformatted value in the element anElement.unformatLocalized();
unformatLocalized Idem above, but using the outputFormat option override passed as a parameter anElement.unformatLocalized(forcedOutputFormat);
isPristine Return true if the current value is the same as when the element first got initialized (not set()) anElement.isPristine();
select Select the formatted element content, based on the selectNumberOnly option anElement.select();
selectNumber Select only the numbers in the formatted element content, leaving out the currency symbol, whatever the value of the selectNumberOnly option anElement.selectNumber();
selectInteger Select only the integer part in the formatted element content, whatever the value of selectNumberOnly anElement.selectInteger();
selectDecimal Select only the decimal part in the formatted element content, whatever the value of selectNumberOnly anElement.selectDecimal();
clear Reset the element value to the empty string '' (or the currency sign, depending on the emptyInputBehavior option value) anElement.clear();
clear Always reset the element value to the empty string '' as above, no matter the emptyInputBehavior option value anElement.clear(true);

Note: Most of them can be chained together, if needed.

Using callback functions with get* methods

All get* methods can accept a callback function as its argument (those methods being get, getNumericString, getFormatted, getNumber and getLocalized). That callback is passed two parameters, the result of the get* method as its first argument, and the AutoNumeric object as its second.

This allows you to directly use the result of the get* functions without having to declare a temporary variable like so:

function sendToServer(value) {
    ajax(value);
}

console.log(`The value ${anElement.getNumber(sendToServer)} has been sent to the server.`);

In other words,

// Using:
anElement.getNumericString(funcCallback);

// Is equivalent to doing:
const result = anElement.getNumericString();
funcCallback(result, anElement);

Note: The callback function behavior is slightly different when called on multiple elements via global.get* methods.

Un-initialize the AutoNumeric element

Method Description Call example
remove Remove the autoNumeric listeners from the element (previous name : 'destroy'). Keep the element content intact. anElement.remove();
wipe Remove the autoNumeric listeners from the element, and reset its value to '' anElement.wipe();
nuke Remove the autoNumeric listeners from the element, then delete the DOM element altogether anElement.nuke();

Node manipulation

Method Description Call example
node Return the DOM element reference of the autoNumeric-managed element anElement.node();
parent Return the DOM element reference of the parent node of the autoNumeric-managed element anElement.parent();
detach Detach the current AutoNumeric element from the shared local 'init' list (which means any changes made on that local shared list will not be transmitted to that element anymore) anElement.detach();
detach Idem above, but detach the given AutoNumeric element, not the current one anElement.detach(otherAnElement);
attach Attach the given AutoNumeric element to the shared local 'init' list. When doing that, by default the DOM content is left untouched. The user can force a reformat with the new shared list options by passing a second argument valued true. anElement.attach(otherAnElement, reFormat = true);

Format and unformat other numbers or DOM elements with an existing AutoNumeric element

You can use any AutoNumeric element to format or unformat other numbers or DOM elements.

This allows to format or unformat numbers, strings or directly other DOM elements without having to specify the options each time, since the current AutoNumeric object already has those settings set.

Method Description Call example
formatOther This use the same function signature that when using the static AutoNumeric method directly (cf. below: AutoNumeric.format), but without having to pass the options anElement.formatOther(12345, { options });
formatOther Idem above, but apply the formatting to the given DOM element by modifying its content directly anElement.formatOther(domElement, { options });
unformatOther This use the same function signature that when using the static AutoNumeric method directly (cf. below: AutoNumeric.unformat), but without having to pass the options anElement.unformatOther('1.234,56 €', { options });
unformatOther Idem above, but apply the unformatting to the given DOM element by modifying its content directly anElement.unformatOther(domElement, { options });

Initialize other DOM Elements

Once you have an AutoNumeric element already setup correctly with the right options, you can use it as many times you want to initialize as many other DOM elements as needed (this works only on elements that can be managed by autoNumeric).

Whenever init is used to initialize other DOM elements, a shared local 'init' list of those elements is stored in the AutoNumeric objects.
This allows for neat things like modifying all those linked AutoNumeric elements globally, with only one call.

Method Description Call example
init Use an existing AutoNumeric element to initialize another single DOM element with the same options const anElement2 = anElement.init(domElement2);
init If true is set as the second argument, then the newly generated AutoNumeric element will not share the same local element list as anElement const anElement2 = anElement.init(domElement2, true);
init Use an existing AutoNumeric element to initialize multiple other DOM elements from an Array, with the same options const anElementsArray = anElement.init([domElement2, domElement3, domElement4]);
init Use an existing AutoNumeric element to initialize multiple other DOM elements from a CSS selector, with the same options const anElementsArray = anElement.init('.currency');

Perform actions globally on a shared 'init' list of AutoNumeric elements

This local 'init' list can be used to perform global operations on all those AutoNumeric elements, with one function call.
To do so, you must call the wanted function by prefixing .global before the method name (ie. anElement.global.set(42)).
Below are listed all the supported methods than can be called globally:

anElement.global.set(2000); // Set the value 2000 in all the autoNumeric-managed elements that are shared on this element
anElement.global.setUnformatted(69);
[result1, result2, result3] = anElement.global.get(); // Return an array of results
[result1, result2, result3] = anElement.global.getNumericString(); // Return an array of results
[result1, result2, result3] = anElement.global.getFormatted(); // Return an array of results
[result1, result2, result3] = anElement.global.getNumber(); // Return an array of results
[result1, result2, result3] = anElement.global.getLocalized(); // Return an array of results
anElement.global.reformat();
anElement.global.unformat();
anElement.global.unformatLocalized();
anElement.global.unformatLocalized(forcedOutputFormat);
anElement.global.update({ options }); // Update the settings of each autoNumeric-managed elements
anElement.global.update({ options1 }, { options2 }, { options3 }); // Idem above, but accepts as many option objects as needed
anElement.global.isPristine(); // Return `true` if *all* the autoNumeric-managed elements are pristine, if their raw value hasn't changed
anElement.global.isPristine(false); // Idem as above, but also checks that the formatted value hasn't changed
anElement.global.clear(); // Clear the value in all the autoNumeric-managed elements that are shared on this element
anElement.global.remove();
anElement.global.wipe();
anElement.global.nuke();

The shared local list also provide list-specific methods to manipulate it:

anElement.global.has(domElementOrAutoNumericObject); // Return `true` if the given AutoNumeric object (or DOM element) is in the local AutoNumeric element list
anElement.global.addObject(domElementOrAutoNumericObject); // Add an existing AutoNumeric object (or DOM element) to the local AutoNumeric element list, using the DOM element as the key
anElement.global.removeObject(domElementOrAutoNumericObject); // Remove the given AutoNumeric object (or DOM element) from the local AutoNumeric element list, using the DOM element as the key
anElement.global.removeObject(domElementOrAutoNumericObject, true); // Idem above, but keep the current AutoNumeric object in the local list if it's removed by itself
anElement.global.empty(); // Remove all elements from the shared list, effectively emptying it
anElement.global.empty(true); // Idem above, but instead of completely emptying the local list of each AutoNumeric objects, each one of those keeps itself in its own local list
[anElement0, anElement1, anElement2, anElement3] = anElement.global.elements(); // Return an array containing all the AutoNumeric elements that have been initialized by each other
anElement.global.getList(); // Return the `Map` object directly
anElement.global.size(); // Return the number of elements in the local AutoNumeric element list
Using callback functions with global.get* methods

Like for their get* methods counterparts, global.get* methods accepts a callback function. However, the callback is executed only once and is passed an array of the get* function results as its first argument, while the AutoNumeric object being passed as its second one.

// Using:
anElement.global.getNumericString(funcCallback);

// Is equivalent to doing:
const [result1, result2, result3] = anElement.global.getNumericString();
funcCallback([result1, result2, result3], anElement);

Form functions

autoNumeric elements provide special functions to manipulate the form they are a part of. Those special functions really work on the parent <form> element, instead of the <input> element itself.

Method Description Call example
form Return a reference to the parent <form> element, null if it does not exist anElement.form();
form(forcedSearch) Idem above, but will force a new search for the parent <form> element, discarding any previously found one anElement.form(true);
formNumericString Return a string in standard URL-encoded notation with the form input values being unformatted anElement.formNumericString();
formFormatted Return a string in standard URL-encoded notation with the form input values being formatted anElement.formFormatted();
formLocalized Return a string in standard URL-encoded notation with the form input values, with localized values anElement.formLocalized();
formLocalized(forcedOutputFormat) Idem above, but with the possibility of overriding the outputFormat option anElement.formLocalized(forcedOutputFormat);
formArrayNumericString Return an array containing an object for each form <input> element, with the values as numeric strings anElement.formArrayNumericString();
formArrayFormatted Return an array containing an object for each form <input> element, with the values as formatted strings anElement.formArrayFormatted();
formArrayLocalized Return an array containing an object for each form <input> element, with the values as localized numeric strings anElement.formArrayLocalized();
formArrayLocalized(forcedOutputFormat) Idem above, but with the possibility of overriding the outputFormat option anElement.formArrayLocalized(forcedOutputFormat);
formJsonNumericString Return a JSON string containing an object representing the form input values. This is based on the result of the formArrayNumericString() function. anElement.formJsonNumericString();
formJsonFormatted Return a JSON string containing an object representing the form input values. This is based on the result of the formArrayFormatted() function. anElement.formJsonFormatted();
formJsonLocalized Return a JSON string containing an object representing the form input values. This is based on the result of the formArrayLocalized() function. anElement.formJsonLocalized();
formJsonLocalized(forcedOutputFormat) Idem above, but with the possibility of overriding the outputFormat option anElement.formJsonLocalized(forcedOutputFormat);
formUnformat Unformat all the autoNumeric-managed elements that are a child to the parent element of this anElement input, to numeric strings anElement.formUnformat();
formUnformatLocalized Unformat all the autoNumeric-managed elements that are a child to the parent element of this anElement input, to localized strings anElement.formUnformatLocalized();
formReformat Reformat all the autoNumeric-managed elements that are a child to the parent element of this anElement input anElement.formReformat();

The following functions can either take a callback, or not. If they don't, the default form.submit() function will be called.

Method Description Call example
formSubmitNumericString(callback) Run the callback(value) with value being equal to the result of formNumericString() anElement.formSubmitNumericString(callback);
formSubmitFormatted(callback) Run the callback(value) with value being equal to the result of formFormatted() anElement.formSubmitFormatted(callback);
formSubmitLocalized(callback) Run the callback(value) with value being equal to the result of formLocalized() anElement.formSubmitLocalized(callback);
formSubmitLocalized(forcedOutputFormat, callback) Idem above, but with the possibility of overriding the outputFormat option anElement.formSubmitLocalized(forcedOutputFormat, callback);

For the following methods, the callback is mandatory:

Method Description Call example
formSubmitArrayNumericString(callback) Run the callback(value) with value being equal to the result of formArrayNumericString() anElement.formSubmitArrayNumericString(callback);
formSubmitArrayFormatted(callback) Run the callback(value) with value being equal to the result of formArrayFormatted() anElement.formSubmitArrayFormatted(callback);
formSubmitArrayLocalized(callback, forcedOutputFormat) Idem above, but with the possibility of overriding the outputFormat option anElement.formSubmitArrayLocalized(callback, forcedOutputFormat);
formSubmitJsonNumericString(callback) Run the callback(value) with value being equal to the result of formJsonNumericString() anElement.formSubmitJsonNumericString(callback);
formSubmitJsonFormatted(callback) Run the callback(value) with value being equal to the result of formJsonFormatted() anElement.formSubmitJsonFormatted(callback);
formSubmitJsonLocalized(callback, forcedOutputFormat) Idem above, but with the possibility of overriding the outputFormat option anElement.formSubmitJsonLocalized(callback, forcedOutputFormat);

Function chaining

Most of those instantiated functions can be chained which allow to be less verbose and more concise.

// On one element
anElement.french()
         .set(42)
         .update({ options })
         .formSubmitJsonNumericString(callback)
         .clear();

// On multiple elements
anElement.global.set(72)
         .global.clear()
         .set(25)
         .global.getNumericString();

Static methods

Without having to initialize any AutoNumeric object, you can directly use the static AutoNumeric class functions.
Note: Some of those functions can be used in Web Workers.

Method Description Call example
areSettingsValid Return true in the settings are valid AutoNumeric.areSettingsValid({ options })
format Format the given number with the given options. This returns the formatted value as a string. AutoNumeric.format(12345.21, { options });
format Idem above, but using a numeric string as the first parameter AutoNumeric.format('12345.21', { options });
format Idem above, but you can pass as many option objects you want to this function, the latter overwriting the previous ones. This allows to correctly format currencies that have a predefined option as its base, but has been slightly modified. AutoNumeric.format('12345.21', { options1 }, { options2 });
format Idem above, using multiple option objects in one array. This way allows for using a pre-defined option name. AutoNumeric.format('12345.21', [{ options1 }, 'euroPos', { options2 }]);
format Format the domElement value (or textContent) with the given options and returns the formatted value as a string. This does not update that element value. AutoNumeric.format(domElement, { options });
formatAndSet Format the domElement value with the given options and returns the formatted value as a string. This function does update that element value with the newly formatted value in the process. AutoNumeric.formatAndSet(domElement, { options });
getAutoNumericElement Return the AutoNumeric object that manages the given DOM element AutoNumeric.getAutoNumericElement(domElement)
AutoNumeric.getAutoNumericElement('#theInput')
getDefaultConfig Return the default autoNumeric settings AutoNumeric.getDefaultConfig()
getFormatted Return the formatted string from the given DOM element or query selector.
This can accept a callback that is passed the result of getFormatted and a reference to the AutoNumeric object.
AutoNumeric.getFormatted(domElement, callback);
AutoNumeric.getFormatted('#theInput')
getLocalized Return the localized unformatted number as a string from the given DOM element or query selector.
This can accept a callback that is passed the result of getLocalized and a reference to the AutoNumeric object.
AutoNumeric.getLocalized(domElement, forcedOutputFormat, callback);
AutoNumeric.getLocalized('#theInput')
getNumber Return the unformatted number as a number from the given DOM element or query selector (The same warnings got the non-static getNumber method applies here too).
This can accept a callback that is passed the result of getNumber and a reference to the AutoNumeric object.
AutoNumeric.getNumber(domElement, callback);
AutoNumeric.getNumber('#theInput')
getNumericString Return the unformatted number as a string from the given DOM element or query selector.
This can accept a callback that is passed the result of getNumericString and a reference to the AutoNumeric object.
AutoNumeric.getNumericString(domElement, callback)
AutoNumeric.getNumericString('#theInput')
getPredefinedOptions Return all the predefined options in one object AutoNumeric.getPredefinedOptions()
getPredefinedOptions Return a specific pre-defined language option object AutoNumeric.getPredefinedOptions().French
isManagedByAutoNumeric Return true if the given DOM element (or selector string) has an AutoNumeric object that manages it. AutoNumeric.isManagedByAutoNumeric(domElement);
AutoNumeric.isManagedByAutoNumeric('#theInput');
localize Unformat and localize the given formatted string with the given options. This returns a string. AutoNumeric.localize('1.234,56 €', { options });
localize Idem as above, but return the localized DOM element value. This does not update that element value. AutoNumeric.localize(domElement, { options });
localizeAndSet Unformat and localize the domElement value with the given options and returns the localized value as a string. This function does update that element value with the newly localized value in the process. AutoNumeric.localizeAndSet(domElement, { options });
mergeOptions Accepts an array of option objects and / or pre-defined option names, and return a single option object where the latter element overwrite the settings from the previous ones AutoNumeric.mergeOptions(['euro', { currencySymbol: '#' }]);
reformatAndSet Recursively format all the autoNumeric-managed elements that are a child to the referenceToTheDomElement element given as a parameter (this is usually the parent <form> element), with the settings of each AutoNumeric elements. AutoNumeric.reformatAndSet(referenceToTheDomElement);
set Set the given value on the AutoNumeric object that manages the given DOM element, if any. Returns null if no AutoNumeric object is found, otherwise returns the AutoNumeric object. AutoNumeric.set(domElement, 42)
AutoNumeric.set('#theInput', 42)
test Test if the given DOM element (or selector string) is already managed by AutoNumeric (if it is initialized) AutoNumeric.test(domElement);
AutoNumeric.test('#theInput');
unformat Unformat the given formatted string with the given options. This returns a numeric string. AutoNumeric.unformat('1.234,56 €', { options });
unformat Idem above, but you can pass as many option objects you want to this function, the latter overwriting the previous ones. This allows to correctly unformat currencies that have a predefined option as its base, but has been slightly modified. AutoNumeric.unformat('241800,02 €', AutoNumeric.getPredefinedOptions().French, { digitGroupSeparator: AutoNumeric.options.digitGroupSeparator.noSeparator });
unformat Idem above, using multiple option objects in one array. This way allows for using a pre-defined option name. AutoNumeric.unformat('1.234,56 €', [{ options1 }, 'euroPos', { options2 }]);
unformat Unformat the domElement value with the given options and returns the unformatted numeric string. This does not update that element value. AutoNumeric.unformat(domElement, { options });
unformatAndSet Unformat the domElement value with the given options and returns the unformatted value as a numeric string. This function does update that element value with the newly unformatted value in the process. AutoNumeric.unformatAndSet(domElement, { options });
unformatAndSet Recursively unformat all the autoNumeric-managed elements that are a child to the referenceToTheDomElement element given as a parameter (this is usually the parent <form> element) AutoNumeric.unformatAndSet(referenceToTheDomElement);
validate Check if the given option object is valid, and that each option is valid as well. This throws an error if it's not. AutoNumeric.validate({ options })
version Return the current AutoNumeric version number (for debugging purpose) AutoNumeric.version();

Formula mode

AutoNumeric provides a quick way to enter and evaluate simple math expressions directly into the element.

Sometimes, you need to quickly calculate the product or the sum of two or more numbers, before entering the result in the AutoNumeric element.
For instance, you might ask yourself "How many months are there in 14 years and 5 months ?", then you'd need to either make a mental calculation, or resort to using a calculator. To speed things up and provide a lean user experience, AutoNumeric provides a formula mode which allows you to enter and evaluate simple math expressions very quickly.

Using our previous example, you would just need to activate the formula mode by entering the equal sign (=) key, then type =14*12 + 5, and finally validate that expression by using the Enter key, or by blurring the field.
Note: if the math expression is invalid, the previous rawValue is set back

By default, this behavior is disabled. If you want to enable the math expression parsing, you need to set the formulaMode option to true:

new AutoNumeric(domElement, { formulaMode: true });

If you want to cancel the math expression edition and exit the formula mode, hit the Escape key.

Allowed characters in formula mode

Simple math expressions are allowed, which means you can use any numeric characters, the decimal point ., as well as the following operators +, -, *, /, ( and ).
Note: parentheses and operators precedence are respected as expected

This allows for evaluating the following math expressions examples:

  • 8 * -12.46
  • 22* (10 - 2)/1.5- -0.5
  • (4+1) * 2 - (104587.23 * 8 - (-7))

Formula mode events

On user validation, if the math expression syntax is invalid, the previous valid rawValue is set back, and the autoNumeric:invalidFormula event is sent. When a valid math expression is accepted, then its result is set(), and the autoNumeric:validFormula event is sent.

Event lifecycle

AutoNumeric elements are transparent to the native input and change events, which means those are correctly sent when using an <input> element managed by AutoNumeric.

In addition to the native events, custom events sent by AutoNumeric elements allows you to hook into the formatting lifecycle, as you see fit:

  • 'autoNumeric:correctedValue' when an invalid value is corrected
  • 'autoNumeric:initialized' when the AutoNumeric element is initialized
  • 'autoNumeric:invalidFormula' when the user tries to validate an invalid math expression
  • 'autoNumeric:invalidValue' when an invalid value is entered (ie. when the raw value is out of the min/max range)
  • 'autoNumeric:rawValueModified' when the rawValue is modified
  • 'autoNumeric:formatted' when all the formatting is done and the formatted string is modified
  • 'autoNumeric:minExceeded' if the minimumValue is not respected
  • 'autoNumeric:maxExceeded' if the maximumValue is not respected
  • 'autoNumeric:validFormula' when the user validate a valid math expression

Note: You can also set if the events triggered by the AutoNumeric elements, custom or native, should bubble up (option eventBubbles) or be cancelable (option eventIsCancelable).

Whenever an AutoNumeric element is initialized, the custom 'autoNumeric:initialized' event is sent.
When using AutoNumeric.multiple() to initialize numerous elements at once, as many 'autoNumeric:initialized' events are sent as there are initialized elements.

Finally, the 'change' event is sent on blur if the value has been changed since the focus one.

Note: the AutoNumeric.format() static function does trigger an 'autoNumeric:formatted' event if the value that the user is trying to format is outside the minimumValue and maximumValue range, with the detail attribute containing the range error message.

AutoNumeric custom events details

The 'autoNumeric:formatted' event has a payload that contains the following detail attribute:

// This is an example of `CustomEvent` object sent by AutoNumeric when its value is formatted:
const theCustomEvent = {
    detail    : {
        oldValue   : "78,00 €",  // The previous formatted value
        newValue   : "788,00 €", // The new formatted value
        oldRawValue: 78,         // The previous raw value
        newRawValue: 788,        // The new raw value
        isPristine : false,      // Is the element value still pristine? In other words, has its value changed since its initialization?
        error      : null,       // The error message as a string, `null` if no errors.
        aNElement  : theAutoNumericObject, // The AutoNumeric object emitting this event
    },
    // ...and the usual `bubbles` and `cancelable` attributes
}

// When caught, you can access the event attributes like so:
function onFormattedEvent(event) {
    if (!event.detail.isPristine) {
        console.log(`The element value has been changed from ${event.detail.oldValue} to ${event.detail.newValue}.`);
    }
}

The 'autoNumeric:rawValueModified' event has a payload that contains the following detail attribute:

// This is an example of `CustomEvent` object sent by AutoNumeric when the `rawValue` is modified:
const theCustomEvent = {
    detail    : {
        oldRawValue: 78,    // The previous raw value
        newRawValue: 788,   // The new raw value
        isPristine : false, // Is the `rawValue` still pristine? In other words, did it changed since the object initialization?
        error      : null,  // The error message as a string, `null` if no errors.
        aNElement  : theAutoNumericObject, // The AutoNumeric object emitting this event
    },
    // ...
}

The 'autoNumeric:initialized' event has a payload that contains the following detail attribute:

// This is an example of `CustomEvent` object sent by AutoNumeric when the object is first initialized:
const theCustomEvent = {
    detail    : {
        newValue   : "788,00 €", // The new formatted value
        newRawValue: 788,        // The new raw value
        error      : null,       // The error message as a string, `null` if no errors.
        aNElement  : theAutoNumericObject, // The AutoNumeric object emitting this event
    },
    // ...
}

The 'autoNumeric:invalidFormula' event has a payload that contains the following detail attribute:

// This is an example of `CustomEvent` object sent by AutoNumeric when the math expression is invalid:
const theCustomEvent = {
    detail    : {
        formula  : '22+35 - (44',        // The invalid formula
        aNElement: theAutoNumericObject, // The AutoNumeric object emitting this event
    },
    // ...
}

The 'autoNumeric:validFormula' event has a payload that contains the following detail attribute:

// This is an example of `CustomEvent` object sent by AutoNumeric when the math expression is valid:
const theCustomEvent = {
    detail    : {
        formula  : '22+35 - (44)',       // The valid formula
        result   : 13,                   // The math expression result
        aNElement: theAutoNumericObject, // The AutoNumeric object emitting this event
    },
    // ...
}

This can then be used within another script.
For instance, you could listen to that event in a Vue.js component template like so:

<vue-autonumeric 
    v-on:autoNumeric:formatted.native="funcCall1"
    v-on:autoNumeric:rawValueModified.native="funcCall2"
    v-on:autoNumeric:initialized.native="funcCall3"
/>

(Check out the official vue-autonumeric component for more info)

Key inputs

Following are listed how AutoNumeric react to different types of key inputs.

By default a 'normal' printable character input (ie. '2' or ',') will result in those events, in that specific order:

  1. 'keydown'
  2. 'autoNumeric:minExceeded' or 'autoNumeric:maxExceeded' if there was a range problem
  3. 'keypress' (this is deprecated and will be removed soon)
  4. 'input'
  5. 'keyup'
  6. 'autoNumeric:formatted' when all the formatting is done
  7. 'autoNumeric:rawValueModified' when the rawValue is modified

Note: Please check below how is structured the payload attached to the event variable. The event detail provides easy access to the old and new value.

When inputting a modifier key (ie. Control), we get:

  1. 'keydown'
  2. 'keyup'
  3. 'autoNumeric:formatted'
  4. 'autoNumeric:rawValueModified'

If Delete or backspace is entered, the following events are sent:

  1. 'keydown'
  2. 'input'
  3. 'keyup'
  4. 'autoNumeric:formatted'
  5. 'autoNumeric:rawValueModified'

If Enter is entered and the value has not changed, the following events are sent:

  1. 'keydown'
  2. 'keypress'
  3. 'keyup'
  4. 'autoNumeric:formatted'
  5. 'autoNumeric:rawValueModified'

If Enter is entered and the value has been changed, the following events are sent:

  1. 'keydown'
  2. 'keypress'
  3. 'change'
  4. 'keyup'
  5. 'autoNumeric:formatted'
  6. 'autoNumeric:rawValueModified'

When a paste is done with the mouse, the following events are sent:

  1. 'input'
  2. 'keydown'
  3. 'input'
  4. 'keyup'
  5. 'keyup'
  6. 'autoNumeric:formatted'
  7. 'autoNumeric:rawValueModified'

And when a paste is done with the keyboard shortcut (ie ctrl+v), the following events are sent:

  1. 'keydown'
  2. 'keydown'
  3. 'input'
  4. 'keyup'
  5. 'keyup'
  6. 'autoNumeric:formatted'
  7. 'autoNumeric:rawValueModified'

Questions

For questions and support please use the Gitter chat room or IRC on Freenode #autoNumeric.
The issue list of this repository is exclusively for bug reports and feature requests.


How to contribute?

Contributors and pull requests are welcome.
Feel free to contact us for any questions.
For more information about how to contribute, please check the CONTRIBUTING file which has more details about it.

In a nutshell :

  • Get the latest source git clone -b next https://github.com/autoNumeric/autoNumeric.git && cd autoNumeric && yarn install
  • Make you changes
  • Lint, build, and run tests yarn lint && yarn build && yarn test
    • If you encounter any linting problems, you can try to automatically fix those with yarn lintfix
  • Create a pull request, and we'll check it out as soon as possible!

Again, be sure to check the CONTRIBUTING guidelines for more details.
Also, feel free to follow our RSS feeds on master and next to keep up with the latest commits.

Dependencies

None!

Older versions

The previous stable autoNumeric version v2.0.13 can be found here, while the older v1.9.46 can be found here.

Check out the upgrade guide if you need help upgrading from version 1.9/2 to version 4.

Related projects

For integration into Rails projects, you can use the autonumeric-rails project.

For integration with PHP Yii2, take a look at the extead/yii2-autonumeric or haifahrul/yii2-autonumeric projects.

For integration into Javascript frameworks, you can use:

Note: Some of those projects may lag with the latest AutoNumeric stable version, or even be incomplete

Other documentation

The old and outdated documentation can be found in the Documentation file.
For some examples and an option code generator for the old v1.9.* version, take a look here.

Licence

autoNumeric is an MIT-licensed open source project, and its authors are credited in AUTHORS.

Support

We'd like to thank JetBrains for supporting us by providing an open-source licence of their tools.


Feel free to donate via Paypal Donate (Robert) or Patreon Donate (Alexandre) to support autoNumeric development.

Comments
  • autoNumeric + Vue.js 2.0 : autoNumeric does not see value updates made via Vue

    autoNumeric + Vue.js 2.0 : autoNumeric does not see value updates made via Vue

    I'm having trouble making autoNumeric work well with Vue.js 2.0.

    Everything looks like it's working (even pasting!), but with one small caveat ; having two inputs,

    • either they share the same v-model (the javascript variable that Vue databind to the html element, which mean that when you change the data in one input, all the other elements sharing the same v-model sees their values updated accordingly),
    • or when one input value change, Vue updates the second input value accordingly

    ...whenever you input a number in the first input, both inputs shows the updated value, but, if you focus on the second input, autoNumeric reverts the updated value to the old one it somehow 'stored' at one point.

    It seems Vue.js updates the input value, but autoNumeric does not see that change happening, hence it somehow keeps the previous value and shows it on focus.

    cf. the codepen where you can see that happening.

    Would you see how to fix that? Does autoNumeric store the input value that gets displayed on focus? Is there a way or a function to update that value when modifying the input value via javascript, and not via a normal user input?

    opened by AlexandreBonneau 42
  • Input is duplicated and reversed on devices with Android < 7.0

    Input is duplicated and reversed on devices with Android < 7.0

    Expected behavior

    Entering 123 should format the input to 123 €

    Actual behavior

    Entering 123 resulted in 123.321 € on SAMSUNG GALAXY S5 (Android 6.0.1, Chrome v61) Entering 123 resulted in 12.321 € on HTC ONE (Android 5.0.2, Chrome v61)

    Steps to reproduce the problem

    1. I tested this using autoNumeric v4.1.0and the browser Chrome version 61 on Android 6.0.1 and Android 5.0.2,
    2. I used the example from http://autonumeric.org

    I've had no problems with autoNumeric on devices using Android > v7.0.

    Best regards, J.

    :lady_beetle: Bug :iphone: Mobile :bangbang: Important! 
    opened by JoHauns 38
  • Allow users to enter out-of-bound numbers, outside of the `minimumValue` and `maximumValue` range

    Allow users to enter out-of-bound numbers, outside of the `minimumValue` and `maximumValue` range

    Currently, if a user sets the minimumValue option to a value superior to zero, it effectively prevent him to delete the input value, since it would mean the rawValue would be equal to 0.

    While this is exactly what the minimumValue option is for, I see a use case where users would want to be able to temporarily clear the element, in order to type their valid values.

    Allowing this will bring some side effects:

    • First, the rawValue will be updated with a potential incorrect out of range value while the user is typing it (the user would then need to manage those error cases),
    • Second, we would need to allow not only the value 0, but any values between 0 and the minimumValue
      • For instance this means that if we have a minimumValue set to 1234, then we would need to allow the user to type 1, 12 and 123 before finally accepting the correct value 1234.

    To that end, we would need to create a new option overrideMinimumValueLimitation (or something equivalent) set to false by default, that would allow a user to input values between 0 and minimumValue in the element, and would then revert to the last good known value on blur if it's still equal out of range.

    This seems not trivial.

    :bulb: Feature request :sparkles: User Experience 
    opened by AlexandreBonneau 23
  • Failing unit tests on macOS with German localization

    Failing unit tests on macOS with German localization

    Current behavior

    On macOS with German localization the unit tests fail.

    Expected behavior

    The unit tests should succeed.

    Steps to reproduce the problem

    1. clone autoNumeric and run yarn && yarn test
    FAILED TESTS:
      The AutoNumeric object
        initialization methods
          ✖ should correctly initialize the AutoNumeric element when the `formatOnPageLoad` option is set
            Firefox 61.0.0 (Mac OS X 10.13.0)
          Expected '12234678.321' to equal '$12,234,678.32'.
          <Jasmine>
          ./test/unit/autoNumeric.spec.js/</</<@webpack://autonumeric/test/unit/autoNumeric.spec.js:1150:12 <- tests.webpack.js:9:705409
          <Jasmine>
    
      Initialization calls
        Initialize a single AutoNumeric object
          ✖ should fail to init when the default value is outside of the min and max limits
            PhantomJS 2.1.1 (Mac OS X 0.0.0)
          TypeError: undefined is not an object (evaluating 'aNInput.remove') in tests.webpack.js (line 9)
          webpack://autonumeric/webpack/universalModuleDefinition:1:0 <- tests.webpack.js:9:1481375
          <Jasmine>
    
      autoNumeric options and `options.*` methods
        `options.*` methods
          ✖ should correctly update the `decimalPlacesShownOnFocus` option
            Firefox 61.0.0 (Mac OS X 10.13.0)
          Expected '2.222,12 €' to equal '2.222,1235 €'.
          <Jasmine>
          ./test/unit/autoNumeric.spec.js/</</<@webpack://autonumeric/test/unit/autoNumeric.spec.js:1483:12 <- tests.webpack.js:9:734042
          <Jasmine>
    
      Instantiated autoNumeric functions
        `selectInteger`
          ✖ should select only the decimal part
            Firefox 61.0.0 (Mac OS X 10.13.0)
          Expected '12.266,123 €' to equal '12.266,123457 €'.
          <Jasmine>
          ./test/unit/autoNumeric.spec.js/</</<@webpack://autonumeric/test/unit/autoNumeric.spec.js:5157:12 <- tests.webpack.js:9:990807
          <Jasmine>
    
      The AutoNumeric event lifecycle
        ✖ should send the 'autoNumeric:formatted' event when formatting is done
          Firefox 61.0.0 (Mac OS X 10.13.0)
        Expected spy formattedEvent to have been called 6 times. It was called 5 times.
        <Jasmine>
        ./test/unit/autoNumeric.spec.js/</<@webpack://autonumeric/test/unit/autoNumeric.spec.js:8420:8 <- tests.webpack.js:9:1305434
        <Jasmine>
    

    I'll try to investigate this further.

    :lady_beetle: Bug :tipping_hand_man: Need reporter feedback :warning: Inactivity detected :globe_with_meridians: i18n 
    opened by DanielRuf 21
  • autoNumeric does not work with Browserify

    autoNumeric does not work with Browserify

    We are using npm to manage our packages, and commonjs + browserify to handle module loading.
    I get the following error during the browserify build: (this is gulp executing browserify):

    Process terminated with code 1.
    events.js:160
          throw er; // Unhandled 'error' event
          ^
    SyntaxError: Unexpected token (51:4) while parsing C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\autonumeric\src\autoNumeric.js while parsing file: C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\autonumeric\src\autoNumeric.js
        at DestroyableTransform.end [as _flush] (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\insert-module-globals\index.js:96:21)
        at DestroyableTransform.<anonymous> (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:115:49)
        at DestroyableTransform.g (events.js:291:16)
        at emitNone (events.js:86:13)
        at DestroyableTransform.emit (events.js:185:7)
        at prefinish (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:465:12)
        at finishMaybe (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:473:7)
        at endWritable (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:485:3)
        at DestroyableTransform.Writable.end (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:455:41)
        at DestroyableTransform.onend (C:\git\Idi.Marketplace\Idi.Marketplace.Web\node_modules\through2\node_modules\readable-stream\lib\_stream_readable.js:495:10)
    

    Looks like an unexpected token while parsing autoNumeric.js

    :rocket: Deployment 
    opened by jsmarsch 21
  • Internet Explorer 11 built-in 'delete input content' action is not picked up by AutoNumeric

    Internet Explorer 11 built-in 'delete input content' action is not picked up by AutoNumeric

    Current behavior

    If I enter a value on an input and press X to delete the value it does clear the input, but if I click out of the input (blur) the value in the input is set back instead of clearing the input,

    DEMO VIDEO: https://screencast.com/t/4DsqHplkYx

    Expected behavior

    DEMO VIDEO: https://screencast.com/t/4DsqHplkYx Once "X" is pressed the input should remain clear.

    Steps to reproduce the problem

    1. Use autoNumeric version 4.1

    Any solution to this?

    :sparkles: User Experience :scream: Windows 
    opened by miankulov-modus 20
  • .autoNumeric('getSettings').rawValue has old value on input event when pasting

    .autoNumeric('getSettings').rawValue has old value on input event when pasting

    I'm working on a Vue.js component that utilizes this plugin and am mostly done working out the quirks when syncing data between the input and the component's state. You can check it out here. It has a little hack by way of handling the paste event to deal with the issue I'm experiencing.

    I think the final piece is solving an issue I'm having when pasting values to the input. I'm using the input event triggered on the input (autoNumeric 2.0) to process the synchronization. It works great when typing, but when I try to paste I get the behavior mentioned in the title. You can test it for yourself here.

    Is there something different I should be trying? Thank you.

    opened by rhyek 20
  • Shift+Ins in FireFox doesn't work

    Shift+Ins in FireFox doesn't work

    In checkPaste function this.valuePartsBeforePaste seems to be undefined in FireFox, when user tries to paste values with Shift+Ins hot key I checked versions 1.9.24, 1.9.34 and 2.0-BETA - this error remains in all of them

    opened by arwyl 20
  • Possible feature request: Minimum and maximum decimal places

    Possible feature request: Minimum and maximum decimal places

    I am working on a project where I need to enable the user to enter a price. The price field should always have at least 2 decimal places, but could contain many more (if dealing with extra-specific and extra-precise prices). The field should always be padded with 2 decimal places, but not more.

    The idea is that the user can, if needed, enter more than 2 decimal places, but if they do not, then only 2 decimal places are show.

    Is it somehow possible already or if not, perhaps this could be considered as a possible future feature?

    opened by ragulka 20
  • If update on focus, brackets doesn't go away for negative amount

    If update on focus, brackets doesn't go away for negative amount

    I want to update the format on focus. Seems like there is some trouble when specifying the negative amount with brackets. If I use 'init' instead of 'update' it works. Is this bug or this is what it supposed to do?

    http://jsfiddle.net/h5zm7geb/

    opened by sk29110 18
  • "Sometimes" Dollar sign get stripped out

    I specified one of form element to have specific autoNumeric Format but when it goes over 1000 pretty often it dollar sign get strip out. Sometimes it works. Here are the way I specified to turn on the autoNumeric and I do this when switching between edit Mode and readOnly mode.

    $j('#form .hasNoChild .budget-value-column input').autoNumeric('init', {aSign: "$", vMax: 9999999.99, wEmpty: 'zero', mDec: 2 })

    opened by sk29110 18
  • formArrayNumericString -> returns NaN

    formArrayNumericString -> returns NaN

    Current behavior

    When using Autonumeric with 8 decimal numbers and only the last 1 or 2 are filled it returns "NaN"

    Expected behavior

    Returning the number.

    Steps to reproduce the problem

    See Js Fiddle

    Link to live example

    jsfiddle

    opened by sitenzo 0
  • Heavy bug with german number formatting

    Heavy bug with german number formatting

    Current behavior

    German numbers with on grouping/thousands dot will be handled on page-load (or ajax-replace) as english numbers so 1.000 gets 1.0 (one thousand is converted to one) 900.000 gets 900 (only if there are no decimal digits)

    Expected behavior

    German numbers between 1.000 und 999.999 should not be changed

    Steps to reproduce the problem

    Save and open following HTML:

    <html>
       <head>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/4.6.0/autoNumeric.js"></script>
          <script>
             window.addEventListener("load", (event) => {
                new AutoNumeric("input", {
                   currencySymbol: "",
                   decimalCharacter: ",",
                   digitGroupSeparator: ".",
                   decimalPlaces: 2
                });
             });
          </script>
       </head>
       <body>
          <input type="text" value="12.345" />value=12.345 - the german 12.345,00 but without decimal places<br />
          <input type="text" value="1.234.567"/>value=1.234.567 - the german 1.234.567,00 but without decimal places<br />
       </body>
    </html>
    

    https://pastebin.com/BdgYVacY

    Fix

    <Also, when creating an extract of your problem, you are likely to find the cause of it, and fix it yourself, :tada: ;)>

    The Problem is in autoNumeric.js (4.6.0) line 10389 in the "_toNumericValue" function.

    The first IF for "normal" (english-styled) numbers also miss-matches for german integers between 1.000 and 999.999. My fix was to check the actual decimalCharacter by changing the original if (AutoNumericHelper__WEBPACK_IMPORTED_MODULE_0_["default"].isNumber(Number(value))) { to if (settings.decimalCharacter == this.getDefaultConfig().decimalCharacter && AutoNumericHelper__WEBPACK_IMPORTED_MODULE_0_["default"].isNumber(Number(value))) {

    (found no static access to AutoNumeric__WEBPACK_IMPORTED_MODULE_0_["default"].options.decimalCharacter.dot)

    Another question:

    Is there a "hidden" (i haven't found it) function to add the decimal digits directly while typing, not afterwards on blur? So when i type "1" in an empty field it gets automatically to "1.00" (in english-format), with cursor staying after "1"?

    opened by dqdrt 0
  • get value from specific input

    get value from specific input

    <input type="text" id="input-1" class="input-auto-numeric">
    <input type="text" id="input-2" class="input-auto-numeric">
    new AutoNumeric.multiple(".input-auto-numeric");
    

    how to get unformatted value from input-1 ??

    opened by donny26utama 0
  • Jquery selector updating from v.1.9 to 4

    Jquery selector updating from v.1.9 to 4

    Hi,

    i'm updating autonumeric at the new version. with autonumeric 1.9 I was able to use the jquery selector, for example $(this).autonumeric.get(). How I can do the same with the new version?

    Thx

    opened by manuTro 0
  • Invalid JS imports (without having an export)

    Invalid JS imports (without having an export)

    Hi! 👋

    Firstly, thanks for your work on this project! 🙂

    We run into problems running esbuild via vite against autoNumeric:

    ✘ [ERROR] No matching export in "node_modules/autonumeric/src/AutoNumericOptions.js" for import "default"
    
        node_modules/autonumeric/src/AutoNumericDefaultSettings.js:31:7:
          31 │ import AutoNumericOptions from './AutoNumericOptions';
             ╵        ~~~~~~~~~~~~~~~~~~
    
    ✘ [ERROR] No matching export in "node_modules/autonumeric/src/AutoNumericEvents.js" for import "default"
    
        node_modules/autonumeric/src/main.js:32:7:
          32 │ import AutoNumericEvents from './AutoNumericEvents';
             ╵        ~~~~~~~~~~~~~~~~~
    
    ✘ [ERROR] No matching export in "node_modules/autonumeric/src/AutoNumericOptions.js" for import "default"
    
        node_modules/autonumeric/src/main.js:33:7:
          33 │ import AutoNumericOptions from './AutoNumericOptions';
             ╵        ~~~~~~~~~~~~~~~~~~
    
    ✘ [ERROR] No matching export in "node_modules/autonumeric/src/AutoNumericDefaultSettings.js" for import "default"
    
        node_modules/autonumeric/src/main.js:34:7:
          34 │ import AutoNumericDefaultSettings from './AutoNumericDefaultSettings';
             ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ✘ [ERROR] No matching export in "node_modules/autonumeric/src/AutoNumericPredefinedOptions.js" for import "default"
    
        node_modules/autonumeric/src/main.js:35:7:
          35 │ import AutoNumericPredefinedOptions from './AutoNumericPredefinedOptions';
             ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    

    This might be the same issue what is discussed in https://github.com/autoNumeric/autoNumeric/issues/727.

    Here is the diff that solved our problems:

    diff --git a/node_modules/autonumeric/src/AutoNumericDefaultSettings.js b/node_modules/autonumeric/src/AutoNumericDefaultSettings.js
    index 3cd373a..705f61e 100644
    --- a/node_modules/autonumeric/src/AutoNumericDefaultSettings.js
    +++ b/node_modules/autonumeric/src/AutoNumericDefaultSettings.js
    @@ -28,7 +28,7 @@
      */
     
     import AutoNumeric from './AutoNumeric';
    -import AutoNumericOptions from './AutoNumericOptions';
    +import './AutoNumericOptions';
     
     /* eslint no-unused-vars: 0 */
     
    diff --git a/node_modules/autonumeric/src/main.js b/node_modules/autonumeric/src/main.js
    index 5334b78..e914ffb 100644
    --- a/node_modules/autonumeric/src/main.js
    +++ b/node_modules/autonumeric/src/main.js
    @@ -29,10 +29,10 @@
      */
     
     import AutoNumeric from './AutoNumeric';
    -import AutoNumericEvents from './AutoNumericEvents';
    -import AutoNumericOptions from './AutoNumericOptions';
    -import AutoNumericDefaultSettings from './AutoNumericDefaultSettings';
    -import AutoNumericPredefinedOptions from './AutoNumericPredefinedOptions';
    +import './AutoNumericEvents';
    +import './AutoNumericOptions';
    +import './AutoNumericDefaultSettings';
    +import './AutoNumericPredefinedOptions';
     
     /* eslint no-unused-vars: 0 */
     
    

    This issue body was partially generated by patch-package.

    opened by mseele 0
Releases(v4.6.0)
  • v4.6.0(Feb 13, 2022)

    This late 4.6.0 release is done here in Github to catch up on the version published on npm for a while now. The latest release on Github was 4.1.0, and since then 164 commits have been done.

    Here are the highlights of the changes since then:

    • New features

      • Introduces the formula mode which allows a user to enter a math expression in the element using the = key, then evaluate it with the Enter one
        • This allows basic calculations when entering expressions like =12*(78/(25+2)) (#542)
        • Adds the formulaMode option, set to false by default, that controls if the formula mode is enabled
      • Adds the Lexer, Parser, Evaluator, ASTNode and Token classes for managing math expressions
      • Adds a typescript definitions file to the library
      • Adds a new option value 'invalid' for the overrideMinMaxLimits option, that will allow users to enter out-of-bound numbers (#543)
      • Adds a new option invalidClass, which default to an-invalid, that defines the CSS class name to use when a contenteditable-enabled element value is invalid
      • Add a feature where emptyInputBehavior could be set to the minimum or maximum value (#476)
        • emptyInputBehavior now accepts either a number (or a string representing a number), or the 'min' or 'max' option
      • Add the new alwaysAllowDecimalCharacter option set to false by default
      • Modify the update() function so that it can accept an array of options (#556)
      • The update() function now does accept predefined option names (ie. 'euro') (#555)
      • This adds support for using scientific notation for setting the input value (ie. aNInput.set('6.1349392e-13');, <input value="7342.561e40">) (#553)
    • Changes

      • From now on, whenever the user sets a minimumValue higher than 0, or a maximumValue lower than 0, a warning will be displayed in the console telling him to perhaps use the overrideMinMaxLimits invalid option. For information, the overrideMinMaxLimits doNotOverride is still the default behavior.
      • Modify the tenTrillions and oneBillion limits to be exact
        • Remove the maximumValue and minimumValue tenTrillionsNoDecimals option, and update tenTrillions so that it equals ten trillions
        • The tenTrillions sub-option is now equal to '10000000000000', and the oneBillion sub-option is now equal to '1000000000'
        • This change was long overdue since we modified in v4.0.0-beta.22 how the number of decimal places was defined by the user using the decimalPlaces options instead of adding a specific number of decimal to the min/max values.
      • Change how the decimal character can be entered (#535):
        • Before, the comma ',' and dot '.' where always accepted
        • Now, only the characters defined in decimalCharacter and decimalCharacterAlternative are accepted
    • Improvements

      • Reduce the size of the generated library by tuning the UglifyJs options
      • The webpack devtool option for the development configuration has been changed from cheap-module-eval-source-map to cheap-source-map; This removes any eval() from the generated dist/autoNumeric.js file, and makes the source maps works in all cases in the browsers (#612)
      • Merge the changes from 4.4.1 while making sure there is no regression with #609; this adds the browser field alongside the main one in package.json (Note: The browser option points to the minified library dist/autoNumeric.min.js)
      • Update the index.html test file to use the un-minified development library dist/autoNumeric.js This allows to temporarily use forbidden functions like console or wrong formatting while debugging, using yarn build:dev
      • Modify _setReadOnly() so that it always sets the element to read-only mode
    • Fixes

      • Fix issue #535 Prevent entering any decimal character when only positive numbers are accepted
      • Fix issue #558 Switch the webpack 4
      • Fix the bug when an input with the negativeBracketsTypeOnBlur options was focused then blurred, it would dispatch a change event.
      • Fix issue #550 The change event is sent twice on change
      • Fixes #561 Webpack bundles the already compiled library when imported in another project
      • Fixes #563 The import AutoNumeric from 'AutoNumeric' line in the readme does not work on case sensitive OS (like Linux)
      • Fixes #521 The input event is not fired on paste if the element is empty or is completely selected beforehand
      • Fixes #566 Add the Turkish predefined currency
      • Fixes #568 Using brackets for negative numbers in AutoNumeric.format returns "undefined"
      • Fix various bugs regarding the incorrect static and instantiated function calls
      • Fix the polyfill so that Array.from() is correctly 'polyfilled' even if the CustomEvent object already exists
      • Fix the CustomEvent polyfill
      • Merges PR #572 Use AutoNumericHelper.contains() instead of String.includes() for the time being
      • Fixes #570 The minified version of AutoNumeric does not expose some of its static functions (ie. AutoNumeric.getNumber())
        • Removing the standard Function.name feature fixes the bug in IE now. In the near future IE users will need to require a polyfill for this.
      • Fix the end-to-end tests so that they are run against AutoNumeric's minified version
      • Fixes #574 The fractional part is converted to an integer if the part on the cursor left-hand side is equal to 0
      • Fixes #580 Allow non-input tags with the readOnly option to set the contenteditable attribute to false
      • Fix the readonly and contenteditable attributes so that they can be updated to read/write mode
      • Fixes #584 Event listeners are not set/reset on option updates
      • Fixes #583 AutoNumeric v4.2.13 forces the contenteditable attribute to true when set on the html source
      • Fixes #526 Memory / speed improvement in options
      • Fixes #585 Internet Explorer 11 throws when freezing the options
      • Fixes AutoNumeric so that elements now correctly accepts entering a decimal char on the far left of a negative number
      • Fixes #559 Allow AutoNumeric to accept the decimal character input even when there is already one in the element
      • Fixes #596 Change event not firing depending on cursor movement
      • Fixes #593 Pasting a negative value over a negative value that as a currency symbol and its numbers selected throws an error
      • Fix the initialization call new AutoNumeric() where using as arguments a string (element selector), a number (initial value) and an array (array of options), in that particular order, would not be recognized
      • Fixes #589 The percentageUS* predefined options do not have the rawValueDivisor option set
      • Fixes #219 'Bug on form reset' that was re-opened
        • AutoNumeric now listens to the reset event on the parent form, and react accordingly if detected
      • Fixes #565 Entering a single minus character in a negativeBracketsTypeOnBlur input invert the currency sign and that minus sign
      • Fixes #594 Currency at wrong position for empty fields with euro/french preset after typing minus sign
      • Fixes #579 Allow emptyInputBehavior to be set to min, max, or a number
      • Fix the emptyInputBehavior validation test when checking the value limits
      • Fixes #609 Uncaught Error: Cannot find module 'autonumeric' on v4.4.1
      • Fixes #598 The unformatOnHover config value isn't used when set to false
      • Fixes a call to _reformatAltHovered() even when the unformatOnHover option was set to false
      • Fix the formula mode so that the custom decimal character set with decimalCharacter is used instead of the default '.' character when writing float numbers
      • Fix how readonly and disabled inputs should not process keyboard events
      • Fixes #611 The html readonly attribute is ignored on initial load
      • Fixes #621 The autoNumeric:formatted event should be triggered when the input field is cleared while continuously pressing the Backspace or Deletekeys
      • Fixes #622 freezeOptions() can create issues in some browsers
      • Fixes #626 Missing the \u0092 digit group separator
      • Fix #602 Numpad decimal separator does not work on IE11 with a keyboard whose numpad decimal key outputs a comma
      • Fixes #621 The autoNumeric:formatted event should be triggered when the input field is cleared while continuously pressing the Backspace or Delete keys (for real this time, see v4.5.2)
      • Fixes #652 On initialization, allowDecimalPadding option 'floats' does not hide the decimal zeroes if set in the html attribute
      • Fixes #647 Caret position is incorrectly set when the currencySymbol in prefix position contains the first value entered (ie. a numeric value)
      • Fixes #656 Input value will undo on focusout when using only Ctrl+Backspace
      • Fixes #675 The caret position is wrongly positioned when setting the raw value to zero on numbers with a prefix currency symbol (The bug was introduced in v4.5.9 with the fix for #647)
      • Fixes #543 Allow users to enter out-of-bound numbers, outside of the minimumValue and maximumValue range
        • This allows users to type temporary invalid numbers when the minimumValue is superior to 0, or the maximumValue is inferior to 0
        • While in this out-of-bound state, the element validity status is set to invalid
        • Users can then target the CSS :invalid and/or :valid state as they wish to display a visual feedback as needed
        • Do note that contenteditable-enabled elements cannot have a validity state set, so AutoNumeric instead sets by default the an-invalid CSS class on such 'invalid' elements
        • Whenever the user type an invalid number (out of range), the new 'autoNumeric:invalidValue' event is sent. When the value is corrected, the new 'autoNumeric:correctedValue' event is sent.
          • Beware; To reduce complexity, the 'autoNumeric:invalidValue' event as well as the 'autoNumeric:minExceeded' or 'autoNumeric:maxExceeded' events are now sent up to three times for a single input; on keypress, keyup and blur
      • Fixes the bug where you could always clear the input even if the limit were preventing you to do so (the last valid value was then set back on blur). Now AutoNumeric correctly prevents you to clear the input if the resulting value is out-of-bound.
      • Fixes #676 36 errors in index.d.ts when using with typescript
        • TypeScript users should now remove the declare module 'autonumeric'; line from their script (cf. PR #677)
      • Fixes the detection of wheel events when using a touchpad/trackball (cf. PR #672)

    You can check the detailed commit log here.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.0(Feb 12, 2018)

    The highlights of this version are:

    • New features

      • AutoNumeric static functions can now be used in web workers (#494)
      • Add the new valuesToStrings option to allow displaying a pre-defined string depending on the rawValue (#450)
      • Allow the positive & negative signs to be specified via the two options positiveSignCharacter and negativeSignCharacter (#478)
      • Add more details to the 'autoNumeric:formatted' event payload (#485)
      • Add a new event hook autoNumeric:rawValueModified that will be sent only when the rawValue is modified (#488)
      • Add a new custom AutoNumeric event 'autoNumeric:initialized' sent as soon as an AutoNumeric element is initialized
      • Add the static set and get* functions that will allow setting the given DOM element on getting its value without having a reference to its AutoNumeric object (#515)
      • Add support for watching external changes when setting the input value directly with Javascript without using the set() method (Note: watching the external changes from textContent is not yet supported) (#513)
      • Add the new option watchExternalChanges (set to false by default) that defines if the AutoNumeric object should watch and react to external changes (not made via .set())
      • Add the new option wheelOn that defines when we should be listening to the wheel event, either on 'hover' or on 'focus' (#456)
    • Changes

      • Change the modifyValueOnWheel default behaviour to act only when the element is focused. If you want to be able to use the mouse wheel on a non-focused AutoNumeric element, you'll now need to press the Shift key while doing so. You can change that behavior back like it was before by setting the new option wheelOn to hover (#456)
      • Allow changing the bubble and cancelable attributes of events sent by AutoNumeric. This adds two new options eventBubbles and eventIsCancelable that defaults to true to manage those event attributes (#524)
      • Modify the static getAutoNumericElement(), test() and isManagedByAutoNumeric() functions so that they accept either a DOM element or a selector string (#514)
      • When the rawValue is allowed to be null and is effectively null, the min/max limits are now ignored
      • Form serialization now outputs the empty string '' on empty inputs, instead of 0 or 0.00 (#512)
    • Improvements

      • Switch to Webpack 3.* for leaner bundle creations (#438)
      • Migration to eslint 4.* for a cleaner codebase (#475)
      • The decimalCharacterAlternative now correctly ignores the 'comma' or 'dot' when set to none (#432)
      • Unit test now use the mocha profile as default instead of progress
    • Fixes

      • Coverage information is back (#490)
      • Workaround a geckodriver bug when trying to input an hyphen (#480)
      • Fix lots of pasting issues (#481, #482, #483, #484, #505, #510, #547)
      • Create workarounds (hacks really) for various IE-related bugs (#495, #516, #518)
      • AutoNumeric.multiple() now correctly add only one event listener to the parent form, if any (#457)
      • The input event is not fired on mouse wheel (#525)
      • Prevent using the wheel event on disabled input elements
      • The value of a read-only field can be changed with a scroll input (#541)
      • Cut text reappears when leaving the field (#527)
      • Input is duplicated and reversed on devices with Android < 7.0 using Android Chrome (#522)
      • Formatted numbers on Android Chrome do not get deleted on blur anymore

    ...and more.

    Source code(tar.gz)
    Source code(zip)
  • v4.0.0(Jul 29, 2017)

    The highlights of this new version are:

    • AutoNumeric is now fully converted to an ES6 module.
    • No more jQuery dependency.
    • AutoNumeric is now a class. You can access the class method directly from the AutoNumeric object (ie. const aNElement = new AutoNumeric(input, {options})); aNElement.set(123).update({options2});).
    • The number of decimal places is now explicitly set via the decimalPlaces option.
    • You can now specify a different number of decimal place to show when focused and unfocused, and for the internal rawValue. If you relied on the number of decimals in minimumValue or maximumValue to define how many decimal places should be shown on the formatted value, or kept as the precision in the rawValue, you now need to explicitly define how many decimal places your want, whatever number of decimal places minimumValue and maximumValue have.
    • You can now 'cancel' any edits made to the element by hitting the Escape key. If no changes are detected, hitting Esc will select the element value (according to the selectNumberOnly option).
    • Undo/Redo are now supported.
    • You can modify the value of the element by using the mouse wheel on it, if modifyValueOnWheel is set. The wheelStep option defines the step to use.
    • An AutoNumeric object can now initialize other DOM elements with init(domElement), which will then use the same options. The AutoNumeric-managed elements that initialized each other share a common list, allowing the user to perform a single action on many elements at once (via the .global.* functions, ie. aNElement.update({options}) to update the options of all the elements, or aNElement.set(42) to set the same value for each elements). The .global.* functions you can use are : set(), setUnformatted(), get(), getNumericString(), getFormatted(), getNumber(), getLocalized(), reformat(), unformat(), unformatLocalized(), update(), isPristine(), clear(), remove(), wipe(), nuke(), has(), addObject(), removeObject(), empty(), elements(), getList() and size(). Managing that shared list is possible via attach() and detach().
    • The options can now be updated one by one using the handy functions aNElement.options.<nameOfTheOption>({newOption}), ie. aNElement.options.currencySymbol('€'). You can also reset the options to the default ones using aNElement.options.reset().
    • Lots of new options (rawValueDivisor, decimalPlaces, decimalPlacesRawValue, decimalPlacesShownOnBlur, serializeSpaces, noEventListeners, readOnly, selectOnFocus, caretPositionOnFocus, etc.).
    • While the AutoNumeric objects provides many methods, you can also directly use the AutoNumeric class static functions without having to instantiate an object. Those methods are version(), test(), validate(), areSettingsValid(), getDefaultConfig(), getPredefinedOptions(), format(), formatAndSet(), unformat. unformatAndSet(), localize(), localizeAndSet(), isManagedByAutoNumeric() and getAutoNumericElement().
    • Lots of new functions (isPristine(), clear(), nuke(), formatOther() and unformatOther() which allows to format/unformat a numeric string or another DOM element with the current object settings, setValue(), etc.).
    • The get() function has been deprecated, in favor of more explicit get* methods : getNumericString(), getFormatted(), getNumber() and getLocalized().
    • By default, new AutoNumeric('.myClass') will only initialize one element. If you want to initialize multiple DOM elements in one go, you need to use the static AutoNumeric.multiple() function. It allows to initialize numerous AutoNumeric objects (on numerous DOM elements) in one call (and possibly pass multiple values that will be mapped to each DOM element).
    • Support for the Android Chrome mobile browser (v57) (this is a work in progress though, since it's quite hard to work around its limitations).
    • Functions can now be chained (ie. aNElement.clear().set(22).formSubmitJsonNumericString().nuke()).
    • Modify how updating the settings works ; before, all modifications to the settings were directly accepted and stored, then we immediately tried to set() back the current value with those new settings. This could lead to an object state where the object value would be out of the minimum and maximum value range, ie. we would accept the range modification, then immediately throw an error since the current value would then be out of range. For instance, if minimumValue equal 0, maximumValue equal 100 and the current element value equal 50, trying to change the minimumValue to 75 will fail, and the minimumValue will be reverted back to0. The new behavior is leaner ; if the new settings do not pass the validate() method or the following set() call fails, then the settings are reverted to the previous valid ones.
    • The rawValueDivisor option allows to display a formatted value different than the raw value. For instance you can display percentages like '1.23%', while keeping the rawValue 0.0123 'unmultiplied', if rawValueDivisor is set to 100.

    And also:

    • The new selectNumber(), selectInteger() and selectDecimal() function to select the element content as needed.
    • The DOM-specific functions to manipulate it ; node() (returns the DOM element managed by AutoNumeric), parent(), form() (returns the parent
      element, if any).
    • More than 20 functions to manages html forms ; how to retrieve info from them, or submit the info (formatted, unformatted, localized).
    • Predefined options so that the user do not have to configure AutoNumeric manually. Those options are dotDecimalCharCommaSeparator, commaDecimalCharDotSeparator, integer, integerPos, integerNeg, float, floatPos, floatNeg, numeric, numericPos, numericNeg, euro, euroPos, euroNeg, euroSpace, euroSpacePos, euroSpaceNeg, percentageEU2dec, percentageEU2decPos, percentageEU2decNeg, percentageEU3dec, percentageEU3decPos, percentageEU3decNeg, dollar, dollarPos, dollarNeg, percentageUS2dec, percentageUS2decPos, percentageUS2decNeg, percentageUS3dec, percentageUS3decPos and percentageUS3decNeg.
    • Some language options are now shipped directly and you can use the language name as a function to activate those settings (ie. aNElement.french()).
    • Better support for contenteditable elements so that AutoNumeric is not only limited to <input> elements.
    • AutoNumeric send the 'autoNumeric:formatted' event whenever it formats the element content.
    • The raw unformatted value can always be accessible with the rawValue attribute (ie. aNElement.rawValue).
    • When pressing the Alt key, you can hover your mouse over the AutoNumeric-managed elements to see their raw value.
    • You can prevent the mouse wheel to increment/decrement an element value by pressing the Shift key while using the mouse wheel.
    • Default values for each options can be easily accessed with an IDE autocompletion when using AutoNumeric.options.|.
    • Support for drag and dropping numbers into AutoNumeric-managed elements.
    • The styleRules option allows to either change the style of the current element based on the rawValue value, or just call any custom callbacks whenever the rawValue changes.
    • Allow setting the rawValue to null, either by setting it directly (ie. aNElement.set(null)), or by emptying the element, if emptyInputBehavior is set to 'null'.
    • All get*() method accepts a callback function. The callback is passed the result of the get* functions as its first argument, and the current AutoNumeric object as its second.
    • Allow initializing an AutoNumeric element with an array of options objects or pre-defined option names (ie. 'euroPos').
    • Add a static AutoNumeric.mergeOptions() function that accepts an array of option objects and / or pre-defined option names, and return a single option object where the latter element overwrite the settings from the previous ones.
    • Lots of bug fixes and code simplification (#387, #391, #393, #397, #399, #398, #244, #396, #395, #401, #403, #408, #320, #411, #412, #413, #417, #423, #415, #418, #409, #416, #414, #427, #248, #425, #264, #250, #404, #434, #440, #442, #447, #448, #449, #454, #453, #388, #461, #452).
    • Better test coverage, both for unit tests and end-to-end tests.
    • Rewrite the documentation (README.md) to make it more 'browsable'.
    • For a more detailed changelog, you can read the changes listed from v3.0.0-beta.1 to v3.0.0-beta.14 and from v4.0.0-beta.1 to v4.0.0-beta.23.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.10(Mar 20, 2017)

    • Fix issue #417 Error thrown in PhantomJS 2.1.1 on Linux under CI Environment
    • Fix the end-to-end tests for issue #403
    • Fix the webdriver.io configuration for the links to jQuery and AutoNumeric libraries
    Source code(tar.gz)
    Source code(zip)
  • v2.0.9(Mar 10, 2017)

    • Fix issue #389 autoNumeric 2.0.7 npm packages causes build error with typescriptify + browserify
    • Fix issue #401 Decimal key from numpad doesn't work in IE11
    • Fix issue #403 The scale* option is broken when using a scale divisor inferior to zero
    Source code(tar.gz)
    Source code(zip)
  • v2.0.7(Jan 31, 2017)

    • Fix issue #384 npm install for version 2.0.4 does not work on Windows machines
    • Fix issue #377 The dist files in the last publish to npmjs were not rebuilt with the fixes pushed to 2.0.1
    • Fix issue #373 The dist files are not included when publishing to npmjs
    • Fix issue #371 The currency symbol is not removed on blur with the default emptyInputBehavior value focus
    • Fix issue #367 The package.json "postinstall" task does not find the target file when not using the dev dependencies
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jan 24, 2017)

    autoNumeric version 2.0.0 brings many changes.

    Lots of those changes are under the hood, but some brings new methods, options and ways to call autoNumeric.

    Too see exactly what changed in detail, feel free to browse the changelog and the updated readme.

    Below are listed in reverse order (newer fix on top) an excerpt of the numerous changes that are bundled in 2.0.0.

    User changes

    • Native input and change are now correctly thrown, making autoNumeric 'transparent' event-wise, without any unneeded e.preventDefault (cf. issue #292)
    • To ease the evolution to v2.0.0, a convertOldOptionsToNewOnes() function has been added and automatically convert old option names to new ones, while outputting warning message if such an old option name is used
    • Pasting is now fully supported (on a single caret or on a selection), cf. feature request #183
    • Multiple options now exists to manage how to behave in case of an invalid paste : error, ignore, clamp, truncate and replace
    • Fix issue #346 Add a showPositiveSign option to display the positive sign wherever needed
    • Default options are now readily available (Fix issue #341 Add some default options in the languageOption object)
    • Arabic and Persian numbers are now supported for pasting and in initial html values (cf. 2.0.0-beta.19)
    • Fix issue #317 allow jumping over the decimal character when the caret is just left of the decimal character and the user enters the decimal character
    • Fix issue #321 Allows more international decimal characters and grouping separators :
      • Allowed grouping separator : ',', '.', '٬', '˙', "'", ' ', '\u2009', '\u202f', '\u00a0' and ''
      • Allowed decimal characters : '.', ',', '·', '⎖' and '٫'
    • Fix issue #228 Do not modify the current selection when trying to input an invalid character
    • Modify the validate() function to show a warning when decimalPlacesOverride is greater than decimalPlacesShownOnFocus.
    • Fix issue #302 leadingZero option deny does not function correctly and deletes some of the zero to the right of the caret
    • Fix issue #303 When focusing on an input having currencySymbolPlacement set as p (prefix)
    • Drastically improve performance by removing duplicated function calls.
    • Allow the autoFormat() function to format numbers represented as a string.
    • Add the scaleDecimalPlaces, scaleSymbol and scaleDivisor options.
    • Add a getLocalized function that return the raw value of the input, but can also return the value localized with a decimal point and negative sign placement chosen by the user (basically, it replace the old get behavior if any user wants it back).
      • Rename the localOutput setting to outputType, and add an option 'number' that makes getLocalized always return a Number, instead of a string.
    • Modify the get function so that it always returns a valid Number or string representing a number that Javascript can interpret.
    • Modify the pNeg default value based on the aSign and pSign values. This leads to better user experience when setting a currency symbol without setting pNeg.
    • Errors are now always thrown. The debug option now only affects the warning messages (used for non-critical errors).
    • Add a validate() method that checks if the given options object is valid.
    • Added support for arbitrary-precision decimal arithmetic
    • Added modified sNumber option that selects only numbers when selection all (with ctrl+a)
    • Rename the old options name to more explicit ones :

    | Old name | | New name | | :-- | :-- | :-: | | aSep | -> | digitGroupSeparator | | nSep | -> | noSeparatorOnFocus | | dGroup | -> | digitalGroupSpacing | | aDec | -> | decimalCharacter | | altDec | -> | decimalCharacterAlternative | | aSign | -> | currencySymbol | | pSign | -> | currencySymbolPlacement | | pNeg | -> | negativePositiveSignPlacement | | aSuffix | -> | suffixText | | oLimits | -> | overrideMinMaxLimits | | vMax | -> | maximumValue | | vMin | -> | minimumValue | | mDec | -> | decimalPlacesOverride | | eDec | -> | decimalPlacesShownOnFocus | | scaleDecimal | -> | scaleDecimalPlaces | | aStor | -> | saveValueToSessionStorage | | mRound | -> | roundingMethod | | aPad | -> | allowDecimalPadding | | nBracket | -> | negativeBracketsTypeOnBlur | | wEmpty | -> | emptyInputBehavior | | lZero | -> | leadingZero | | aForm | -> | formatOnPageLoad | | sNumber | -> | selectNumberOnly | | anDefault | -> | defaultValueOverride | | unSetOnSubmit | -> | unformatOnSubmit | | outputType | -> | outputFormat | | debug | -> | showWarnings |

    Dev changes

    • Fix issue #345 Setup continuous integration testing (with Travis CI)
    • Fix issue #310 Setup Webdriver.io for end-to-end (e2e) testing
    • Fix issue #354 Setup automated coverage tests (with Coveralls)
    • Fix issue #328 Switch from npm to yarn
    • Switch to eslint
    • Mass rename functions to gives them a more explicit name :

    | Old name | | New name | | :-- | :-- | :-: | | autoCheck() | -> | checkIfInRangeWithOverrideOption() | | autoRound() | -> | roundValue() | | autoGroup() | -> | addGroupSeparators() | | autoStrip() | -> | stripAllNonNumberCharacters() | | fixNumber() | -> | modifyNegativeSignAndDecimalCharacterForRawValue() | | presentNumber() | -> | modifyNegativeSignAndDecimalCharacterForFormattedValue() | | negativeBracket() | -> | toggleNegativeBracket() | | autoGet() | -> | getCurrentElement() | | getHolder() | -> | getAutoNumericHolder() | | autoSave() | -> | saveValueToPersistentStorage() | | _setPosition() | -> | _setCaretPosition() | | _signPosition() | -> | _getSignPosition() | | _formatQuick() | -> | _formatValue() |

    • Upgrade the setElementSelection() function so that it can accept only one caret position.
    • Add a failOnUnknownOption option which allows autoNumeric to strictly analyse the options passed, and fails if an unknown options is used in the settings object.
    • Add a isNumber() helper function to test if a value is a number, or a string representing a number.
    • Add a isInt() helper function to test if a value is a 'real' integer.
    • Create an AutoNumericHolder ES6 class to store the field properties of an autoNumeric element.
    • Add a key() helper function to retrieve an event keyCode.
    • Complete and improve some JSDoc.
    • Rename runCallbacks() into runCallbacksFoundInTheSettingsObject().
    • Simplify decLength() function, as well as removing unnecessary code before each call to this function.
    • Rename decLength() to maximumVMinAndVMaxDecimalLength().
    • Improve autoCode() call hierarchy.
    • Merge autoCode() into getInitialSettings().
    • Caches an additional regex.
    • Rename some functions and variables to make them more explicit.
    • Refactor autoGroup() to use switch statements.
    • Refactor how dPos was used to make it more understandable.
    • Rename keepOriginalSettings into keepAnOriginalSettingsCopy().
    • Simplify autoSave() so that it directly uses the element as an argument, instead of a jQuery reference.
    • Rename the AutoNumericHolder init() function to _updateFieldProperties().
    • Rename the AutoNumericHolder functions that should be private.
    • Rename processAlways() into _processCharacterDeletion(), and simplify it so that if does not do two things at the same time.
    • Rename processKeypress() into _processCharacterInsertion(), and simplify it so that if does not do two things at the same time.
    • Merge some conditions in _formatQuick().
    • Remove the need for a jQuery dependency in the events listeners.
    • Convert some jQuery event listeners to pure JS event listeners.
    • Convert some jQuery-specific functions to native JS ones (ie. $this.val() to e.target.value).
    • Simplify the event listeners by removing any unused returns.
    • Remove unnecessary getHolder() calls in the event listeners.
    • Add an onBlur event listener, allowing us to trigger change events as needed.
    • Reduce getInitialSettings() length by a great deal, making it easier to read and understand.
    • The getInitialSettings() functions now calls the calculateVMinAndVMaxIntegerSizes(), correctMDecOption(), setsAlternativeDecimalSeparatorCharacter(), cachesUsualRegularExpressions() and transformOptionsValuesToDefaultTypes() functions.
    • Refactor the update() code into getInitialSettings(), which allows to remove the autoCode() calls from the AutoNumericHolder constructor and the _updateFieldProperties() function.
    • Remove the need for jQuery in getSettings().
    • Complete the autoFormat() tests and check for the value validity.
    • Remove the sendCustomEvent() function and replace it by the triggerEvent() one (and remove createCustomEvent() as well).
    • Complete the autoUnFormat() tests and check for the value validity.
    • Modify the autoUnFormat() behavior so that when given a number (a real one or a string representing one), the function always return a 'real' number, whatever the options passed.
    • Modify the eslint 'radix' rule to allow for always specifying a radix for the parseInt function.
    • Comment out the default Jasmine test in order to see a 100% success without any skipped tests.
    • Fix the clean:build npm script so that it does not try to remove an inexistant folder.
    • Add a areSettingsValid() method that return true if the options object is valid.
    • Add multiple helper functions isBoolean, isNull, isTrueOrFalseString, isObject, isEmptyObj, hasDecimals, decimalsPlaces.
    • Add a warning() method that output warning message to the console.
    • Rename originalSettings to keepOriginalSettings to better convey what this function is doing.
    • Fix the roundingMethod option default value to 'S' (Round-Half-Up Symmetric).
    • Prepare the code base for future Jasmine tests
    • Add initial babel support
    • Add uglify and npm-build-process support
    • Add npm support for building the minified version
    • Modify & improve the shim for throwing the input event

    Other fixes

    • Fix issue #326 Pasting a single decimal character into an input that has none does not work
    • Fix issue #322 Pasting a string containing a comma set the caret position at the wrong position
    • Fix issue #330 The negativePositiveSignPlacement option can be ignored in some cases
    • Fix issue #339 get returns '0' when the input is empty even if emptyInputBehavior is not equal to 'zero'
    • Fix issue #319 So the 'get' method returns a negative value when there is a trailing negative sign
    • Fix issue #327 So the entire content is selected when tabbing in
    • Fix issue #306 Under FireFox the caret should not be allowed to move right when all zero present in the decimals
    • Fix issue #318 this.selection can be uninitialized if you focus on an input via the Tab key
    • Fix issue #306 when { leadingZero: 'deny' } and proper caret placement
    • Modify decimalPlaces() so that it always return the number of decimal places (ie. 0 instead of null if there is none).
    • Fix issue #283 Bad caret placement when using lZero and entering a 0 on a value superior to 1
    • Make the 'enter' key send a change event when used and the value has been changed
    • Modify the validate() test on the mDec option to allow for a positive integer too
    • Reorganize the init function code to check for critical error first, before doing other calculus
    • Fix issue #246 When focusing single value field with tab, input of same number is impossible
    • Fix issue #247 autoNumeric + Vue.js 2.0 : autoNumeric does not see value updates made via Vue
    • Fix issue #251 .autoNumeric('getSettings').rawValue has old value on input event when pasting
    • Fix a bug in unSetOnSubmit option to handle non autoNumeric controlled inputs
    Source code(tar.gz)
    Source code(zip)
    autoNumeric_v2.0.0.7z(291.21 KB)
    autoNumeric_v2.0.0.tar.gz(461.56 KB)
    autoNumeric_v2.0.0.zip(457.06 KB)
  • 1.9.43(Dec 19, 2015)

  • v1.9.42(Nov 20, 2015)

  • v1.9.40(Oct 27, 2015)

  • v1.9.39(Oct 27, 2015)

  • v1.9.38(Oct 27, 2015)

  • v1.9.37(Oct 27, 2015)

    Added / fixed support for asp.Net WebForm postback. During postback the default value is re-rendered showing the updated value Because autoNumeric cannot distinguish between a page re-load and asp.net form postback, the following HTML data attribute is REQUIRED (data-an-default="same value as the value attribute") to prevent errors on postback Example:

    Source code(tar.gz)
    Source code(zip)
  • v1.9.36(Oct 27, 2015)

    Rewrote the "getString" & "getArray" methods to index successful elements and inputs that are controlled by autoNumeric. This ensures the proper input index is used when replacing the formatted value. Added support for FireFox for Mac meta key "keycode 224" - Thanks Ney Estrabelli

    Source code(tar.gz)
    Source code(zip)
  • v1.9.35(Oct 27, 2015)

  • v1.9.34(Oct 27, 2015)

  • v1.9.33(Oct 27, 2015)

  • v1.9.32(Oct 27, 2015)

    Fixed bug when the "update" method is called in the "onfocus" event Fixed the "getString" & "getArray" methods when multiple inputs share the same name - Thanks Retromax Fixed bug in "ctrl + v" paste event to properly round

    Source code(tar.gz)
    Source code(zip)
  • 1.9.30(Jan 13, 2015)

  • 1.9.28(Jan 12, 2015)

Owner
AutoNumeric
Manage all the AutoNumeric-related projects
AutoNumeric
This web application retrieves real live data from the SpaceX API

This web application retrieves real live data from the SpaceX API. It provides commercial and scientific space travel services, by allowing users to book rockets and join selected space missions.

Sahar Abdel Samad 12 Aug 9, 2022
Type-Safe Errors for JS & TypeScript

Type-Safe Errors for JS & TypeScript

Gio 1.4k Jan 6, 2023
API routes are great for APIs, but for small projects where you have to access server data or hide application logic, you can just call a server function from the client.

API routes are great for APIs, but for small projects where you have to access server data or hide application logic, you can just call a server function from the client.

null 3 Mar 6, 2022
The perfect library for adding search, sort, filters and flexibility to tables, lists and various HTML elements. Built to be invisible and work on existing HTML.

List.js Perfect library for adding search, sort, filters and flexibility to tables, lists and various HTML elements. Built to be invisible and work on

Jonny Strömberg 10.9k Jan 1, 2023
Drag and drop library for two-dimensional, resizable and responsive lists

GridList Drag and drop library for a two-dimensional resizable and responsive list of items Demo: http://hootsuite.github.io/grid/ The GridList librar

Hootsuite 3.6k Dec 14, 2022
A user script for the web that allows you to view and edit files in the Godot Web Editor

Godot-Web-File-Manager This is a user script for the web that allows you to view and edit files in the Godot Web Editor. You can even use this to enab

Roujel Williams 4 Jan 31, 2022
Garçon is a slack bot designed for recommending restaurants and order lunches for you from buy.am delivery service.

Garçon What is it about ? Garçon is a slack bot designed for recommending restaurants and order lunches for you from buy.am delivery service.

Paruyr Muradian 4 Jul 23, 2022
A high-performance, dependency-free library for animated filtering, sorting, insertion, removal and more

MixItUp 3 MixItUp is a high-performance, dependency-free library for animated DOM manipulation, giving you the power to filter, sort, add and remove D

Patrick Kunka 4.5k Dec 24, 2022
JavaScript Survey and Form Library

SurveyJS is a JavaScript Survey and Form Library. SurveyJS is a modern way to add surveys and forms to your website. It has versions for Angular, jQue

SurveyJS 3.5k Jan 1, 2023
Extensive math expression evaluator library for JavaScript and Node.js

?? Homepage Fcaljs is an extensive math expression evaluator library for JavaScript and Node.js. Using fcal, you can perform basic arithmetic, percent

Santhosh Kumar 93 Dec 19, 2022
Browser fingerprinting library with the highest accuracy and stability.

FingerprintJS is a browser fingerprinting library that queries browser attributes and computes a hashed visitor identifier from them. Unlike cookies a

FingerprintJS 18.1k Dec 31, 2022
This is a facebook messenger clone.You can comminicate to other at realtime

?? facebook-messenger This is a facebook messenger clone.You can comminicate to other at realtime ?? ⚡ LIVE To check out the live demo of this app ABO

null 22 Sep 11, 2022
NatsirtMC is a lightweight app allowing you to connect to any Minecraft server without having Minecraft open

NatsirtMC the only way to grind without grinding NatsirtMC is a lightweight app allowing you to connect to any Minecraft server without having Minecra

tristan 3 Dec 26, 2022
A code that allows you to get custom spotify rich presence

Spotifycord A code that allows you to get custom spotify rich presence! The index.js is the main file. server.js prevents your repl from going to slee

Phantom 19 Oct 7, 2022
A simple server application that allows you to perform Wake-on-LAN remotely with a web interface

WoL Helper A simple server application that allows you to perform Wake-on-LAN remotely with a web interface. Usage Install: npm install -g wol-helper

Hongbo 5 Jul 27, 2022
A platform detection library.

Platform.js v1.3.6 A platform detection library that works on nearly all JavaScript platforms. Disclaimer Platform.js is for informational purposes on

BestieJS Modules 3.1k Dec 31, 2022
A benchmarking library. As used on jsPerf.com.

Benchmark.js v2.1.4 A robust benchmarking library that supports high-resolution timers & returns statistically significant results. As seen on jsPerf.

BestieJS Modules 5.3k Dec 28, 2022
A wrapper library for Jitsi Meet that adds audio spatialization, to be able to create virtual meeting rooms.

A wrapper library for Jitsi Meet that adds audio spatialization, to be able to create virtual meeting rooms.

Sean T. McBeth 1.1k Dec 27, 2022
Solid.js library adding signaling to built-in non-primitives

This package provides signaled versions of Javascript's built-in objects. Thanks to it, all theirs properties will be automatically tracked while using standard API.

Maciej Kwaśniak 40 Dec 29, 2022