diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 69465d6..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: ci-docs -on: - push: - branches: - - main -jobs: - deploy: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 - with: - python-version: 3.x - - run: pip install mkdocs-material - - run: mkdocs gh-deploy --force diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 79152e0..0000000 --- a/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.cache -*.mm - -.idea diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404.html b/404.html new file mode 100644 index 0000000..2bf464d --- /dev/null +++ b/404.html @@ -0,0 +1,1453 @@ + + + +
+ + + + + + + + + + + + + + + + + + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
+a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
+b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
+c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
+d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
+e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
+f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
+g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
+h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
+i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
+h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
+i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
+j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
+k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
+l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
+a. License grant.
+A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
+B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
+Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
+Term. The term of this Public License is specified in Section 6(a).
+Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
+Downstream recipients.
+A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
+B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
+C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
+b. Other rights.
+Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
+Patent and trademark rights are not licensed under this Public License.
+To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
+Your exercise of the Licensed Rights is expressly made subject to the following conditions.
+a. Attribution.
+A. retain the following if it is supplied by the Licensor with the Licensed Material:
+i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
+ii. a copyright notice;
+iii. a notice that refers to this Public License;
+iv. a notice that refers to the disclaimer of warranties;
+v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
+B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
+C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
+You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
+If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
+b. ShareAlike.
+In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
+The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
+You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
+You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
+Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
+a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
+b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
+c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
+For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
+a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
+b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
+c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
+a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
+b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
+automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
+automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
+For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
+c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
+d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
+a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
+b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
+a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
+b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
+c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
+d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
+ + + + + + + + + + + + + +AutoNumeric is an MIT-licensed open source project, and its authors are credited in AUTHORS. Check here for more information.
+Copyright © 2016-2023 Alexandre Bonneau alexandre.bonneau@linuxfr.eu and contributors
+Copyright © 2009-2016 Robert J. Knothe bob@decorplanit.com and contributors
Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sub license, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions:
+The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE.
+ + + + + + + + + + + + + +negativePositiveSignBehavior
for the managing the '-' and '+' key behaviornegativePositiveSignBehavior
to true
will allow the toggling, while setting it to false
will disable it; this means that when hitting the '-' key, the value will always be set to its negative value, and hitting the '+' key will always set the element to its positive value (given the minimum and maximum value allows this)negativePositiveSignBehavior: AutoNumeric.options.negativePositiveSignBehavior.toggle
in your options' configuration.positiveSignCharacter
optionmodifyValueOnUpDownArrow
and upDownStep
formArrayNumericString()
validate()
function for the allowDecimalPadding
option@wdio/sync
package in favor of using async/await everywhere, and updating all the keys()
calls to use the Webdriver Key
object, and arrays of individual charactersvalidate()
function with additional tests for the new allowDecimalPadding
option as a numberthis.onGoingRedo
)styleRules
callback is passed as a parameterv4.6.0
invalidClass
, which default to an-invalid
, that defines the CSS class name to use when a contenteditable-enabled element value is invalid'invalid'
for the overrideMinMaxLimits
option, that will allow users to enter out-of-bound numbersminimumValue
and maximumValue
rangeminimumValue
is superior to 0
, or the maximumValue
is inferior to 0
invalid
:invalid
and/or :valid
state as they wish to display a visual feedback as neededan-invalid
CSS class on such 'invalid' elements'autoNumeric:invalidValue'
event is sent. When the value is corrected, the new 'autoNumeric:correctedValue'
event is sent.'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 blurminimumValue
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._isWithinRangeWithOverrideOption()
functiondeclare module 'autonumeric';
line from their script (cf. PR #677)v4.5.9
with the fix for #647)currencySymbol
in prefix position contains the first value entered (ie. a numeric value)allowDecimalPadding
option 'floats'
does not hide the decimal zeroes if set in the html attributeautoNumeric: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
)ng-angular
component in the README\u0092
digit group separatorfreezeOptions()
can create issues in some browsersautoNumeric:formatted
event should be triggered when the input field is cleared while continuously pressing the Backspace
or Delete
keysreadonly
attribute is ignored on initial loaddecimalCharacter
is used instead of the default '.'
character when writing float numbers=12*78
=
key, then evaluate it with the Enter
oneformulaMode
option, set to false
by default, that controls if the formula mode is enabledLexer
, Parser
, Evaluator
, ASTNode
and Token
classes for managing math expressionsdevtool
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 browsers4.4.1
while making sure there is no regression with #609; this adds the browser
field alongside the main
one in package.json
browser
option points to the minified library dist/autoNumeric.min.js
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
_reformatAltHovered()
even when the unformatOnHover
option was set to false
unformatOnHover
config value isn't used when set to false
4.4.1
: "Modify the package.json
configuration main
field to browser
"package.json
configuration main
field to browser
window
objectemptyInputBehavior
could be set to the minimum or maximum valueemptyInputBehavior
now accepts either a number (or a string representing a number), or the 'min'
or 'max'
optionemptyInputBehavior
validation test when checking the value limitsemptyInputBehavior
to be set to min, max, or a numbernegativeBracketsTypeOnBlur
input invert the currency sign and that minus signreset
event on the parent form, and react accordingly if detected _onPaste()
handler by removing duplicated partsnew 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 recognizedpercentageUS*
predefined options do not have the rawValueDivisor
option settenTrillions
and oneBillion
limits to be exactmaximumValue
and minimumValue
tenTrillionsNoDecimals
option, and update tenTrillions
so that it equals ten trillionstenTrillions
sub-option is now equal to '10000000000000'
, and the oneBillion
sub-option is now equal to '1000000000'
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.alwaysAllowDecimalCharacter
option set to false
by defaultv4.2.13
forces the contenteditable attribute to true
when set on the html sourcereadOnly
option to set the contenteditable
attribute to false
readonly
and contenteditable
attributes so that they can be updated to read/write mode_setReadOnly()
so that it always sets the element to read-only mode_setReadWrite()
function that sets the element to read-write mode_setWritePermissions()
function that sets the element read only/write mode according to the readOnly
settingAutoNumeric.getNumber()
)Function.name
feature fixes the bug in IE now. In the near future IE users will need to require a polyfill for this.Array.from()
is correctly 'polyfilled' even if the CustomEvent
object already existsCustomEvent
polyfillAutoNumericHelper.contains()
instead of String.includes()
for the time beinglatest
to env
input
event is not fired on paste
if the element is empty or is completely selected beforehandimport AutoNumeric from 'AutoNumeric'
line in the readme does not work on case sensitive OS (like Linux)change
event is sent twice on changenegativeBracketsTypeOnBlur
options was focused then blurred, it would dispatch a change
event.update()
function so that it can accept an array of optionsupdate()
function does not accept predefined option names (ie. 'euro'
)aNInput.set('6.1349392e-13');
, <input value="7342.561e40">
)','
and dot '.'
where always accepteddecimalCharacter
and decimalCharacterAlternative
are accepted.travis.yml
file so that the dist
file are built on the CI server.npmignore
file so that the npm autonumeric package can be installeddist/*
files that can be generated using yarn build
, those files are now generated and published to npm automatically when tagging a commit.v4.1.0
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.
+0
drop the current selection, if 0 is out of the limit boundariesdecimalCharacterAlternative
option does not ignore the comma when it's set to none
input
event listener_stripAllNonNumberCharacters
and _convertToNumericString()
functions by creating a _normalizeCurrencySuffixAndNegativeSignCharacters()
function_stripAllNonNumberCharacters()
to _stripAllNonNumberCharactersExceptCustomDecimalChar()
_stripAllNonNumberCharacters()
function that also normalize the decimal characterskipFirstAutoStrip
and skipLastAutoStrip
regexdecimalCharacterAlternative
into the decimalCharacter
when stripping the value_addBrackets()
and _setBrackets()
_removeBrackets()
calls_convertToNumericString()
so that it normalize the positive sign and remove the brackets if any_processCharacterDeletionIfTrailingNegativeSign()
so contains()
is called only once'autoNumeric:initialized'
sent as soon as an AutoNumeric element is initializedcontenteditable
elementsdisabled
element should not be possiblewheel
event on disabled
input elements.input
event is not fired on mouse wheelvaluesToStrings
is ignored when using the static format()
and unformat()
functionswatchExternalChanges
to react to external changes
+ By default, an AutoNumeric element only format the value set with the .set()
function.
+ If you want the element to watch and format value set by third party script using the aNElement.node().value = 42
notation, then you need to set the watchExternalChanges
option to true
.bubble
and cancelable
attributes of events sent by AutoNumericeventBubbles
and eventIsCancelable
that defaults to true
to manage the event attributes.AutoNumeric.multiple()
generate many submit
event listeners on the parent form
drop
event handler removal that was omitted.aNFormHandlerMap
Map on the window
object, that keep track of all submit
event handler for each <form>
element that has at least one AutoNumeric-managed element child.modifyValueOnWheel
default behaviour to act only when the element is focusedwheelOn
option that will define when the wheel
event will increment/decrement the element value.
+ By default the wheel
event is only used when the element is focused (wheelOn
is set to 'focus'
), but you can also use the 'hover'
option if you want to keep the previous behavior.
+ Note: There is a small caveat since the Shift + mouse wheel event
is reserved by browsers for horizontal scrolling, using the Shift
key and the wheelOn
option set to 'hover'
will only scroll the page while the mouse is hovered over the AutoNumeric-managed element. Once it's out of the way, the page won't scroll since you'll be holding the Shift
key. You'll then be able to scroll the page normally without having to hold that Shift
key.value
directly with Javascript without using the set()
method is not supported
+ From now on, if an external change is detected when a script modify the input value
attribute directly, AutoNumeric tries to format the new value.
+ Note: watching the external changes to textContent
is not supported yet._onFocusInAndMouseEnter()
where setElementValue()
was called multiple times in a rowAutoNumeric.events.formatted
event so that only one is sent for each user actionAutoNumeric.events.formatted
event is not sent anymore when wiping an AutoNumeric objectallowDecimalPadding
set to 'floats'
when decimalPlaces
is different from 0
output a warninggetAutoNumericElement()
, test()
and isManagedByAutoNumeric()
functions so that they accept either a DOM element or a selector stringset
and get*
functions_initialCaretPosition()
should never be called when the caretPositionOnFocus
option is null
0
instead of an empty value on empty inputs
+ This fix changes how form serialization is done, by outputting the empty string on empty inputs, instead of 0
or 0.00
.readOnly
element should not be possibletwoScaled
choice for the digitalGroupSpacing
option cannot be validatedbrowser.execute()
calls so that hardcoded DOM ids are not used anymoredecimalPlacesOverride
option without indicating it's deprecatedvalue
attribute adds a zero on the formatted value on page loadAutoNumeric.multiple()
fail on IE11 on unknown Array.from()
formatOnPageLoad
option is set to false
, neither the rawValue
nor the element value are settest/unit
directory.'autoNumeric:formatted'
event payloadautoNumeric:rawValueModified
that will be sent only when the rawValue
is modified'-'
character.'-'
) character was not correctly accepted under Firefox.
+ This was due to the fact that the wrong keyCode 173
is sent instead of 189
like in all the other browsers for that character.'+'
or '-'
does not toggle the positive state, and only move the caret from one character to the left._checkPaste()
so that it's not processed any more times if the element has already been formatted.rawValue
is allowed to be null
and is effectively null
, the min/max limits are ignored.this.formatted
is used so it tracks if the element value has been formatted already. If that's the case, prevent further format calculations.
+ This is a start and this.formatted
usage should be reviewed in depth.valuesToStrings
option to allow displaying a pre-defined string when the rawValue
equal a specific valueAutoNumeric.format()
and AutoNumeric.unformat()
do not accept named optionsformat()
and unformat()
functions ignores the rawValueDivisor
optionAutoNumeric.unformat()
that used the number of decimal places shown on focus instead of the one for the raw value.format()
function does not keep the negative signAutoNumeric.format()
function does not accept DOM element as its first parameterv4.0.0
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});
).decimalPlaces
option.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.Escape
key. If no changes are detected, hitting Esc
will select the element value (according to the selectNumberOnly
option).modifyValueOnWheel
is set. The wheelStep
option defines the step to use.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()
.aNElement.options.<nameOfTheOption>({newOption})
, ie. aNElement.options.currencySymbol('€')
.
+ You can also reset the options to the default ones using aNElement.options.reset()
.rawValueDivisor
, decimalPlaces
, decimalPlacesRawValue
, decimalPlacesShownOnBlur
, serializeSpaces
, noEventListeners
, readOnly
, selectOnFocus
, caretPositionOnFocus
, etc.).version()
, test()
, validate()
, areSettingsValid()
, getDefaultConfig()
, getPredefinedOptions()
, format()
, formatAndSet()
, unformat
. unformatAndSet()
, localize()
, localizeAndSet()
, isManagedByAutoNumeric()
and getAutoNumericElement()
.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.).get()
function has been deprecated, in favor of more explicit get*
methods : getNumericString()
, getFormatted()
, getNumber()
and getLocalized()
.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).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:
+selectNumber()
, selectInteger()
and selectDecimal()
function to select the element content as needed.node()
(returns the DOM element managed by AutoNumeric), parent()
, form()
(returns the parent 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
.aNElement.french()
).contenteditable
elements so that AutoNumeric is not only limited to <input>
elements.'autoNumeric:formatted'
event whenever it formats the element content.rawValue
attribute (ie. aNElement.rawValue
).Alt
key, you can hover your mouse over the AutoNumeric-managed elements to see their raw value.Shift
key while using the mouse wheel.AutoNumeric.options.|
.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.rawValue
to null
, either by setting it directly (ie. aNElement.set(null)
), or by emptying the element, if emptyInputBehavior
is set to 'null'
.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.'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).
+v3.0.0-beta.1
to v3.0.0-beta.14
and from v4.0.0-beta.1
to v4.0.0-beta.23
.noSeparatorOnFocus
option to showOnlyNumbersOnFocus
options.historySize()
method that allows to update the historySize
optionthis.settings.rawValue
to this.rawValue
. This prevent polluting the settings object.rawValueDivisor
option to display a formatted value different than the raw value.
+ This allows for instance to display percentages like '1.23%'
, while keeping the rawValue
0.0123
'unmultiplied', if rawValueDivisor
is set to 100
.blur
event listeners into one.this.isWheelEvent
, this.isDropEvent
and this.isEditing
attributes to track the wheel
and drop
events, as well as when the user is manually editing the element value._setRawValue()
to divide the rawValue
if rawValueDivisor
is set.scaleDivisor
option where it did not check that it should not be equal to 0
.allowDecimalPadding
when decimalPlacesShownOnBlur
or decimalPlacesShownOnFocus
is set.divisorWhenUnfocused
so that it throws if it's set to 1
.divisorWhenUnfocused
to 1
will throw._trimLeadingAndTrailingZeros()
so that it manages null
values correctly (ie. it returns null
instead of '0'
if passed null
).null
value.percentage*
so that the rawValueDivisor
is set to 100
.divisorWhenUnfocused
option value from doNotActivateTheScalingOption
to none
.getNumericString()
so that it returns null
when the rawValue
is null
._calculateDecimalPlaces()
function into two _calculateDecimalPlacesOnInit()
and _calculateDecimalPlacesOnUpdate()
.settings
object are now run before modifying the negativePositiveSignPlacement
option.decimalPlaces
option.
+ Before, this was overriding any other decimalPlaces*
options passed in the same object.
+ Now, the decimalPlaces
value is only used if the other decimalPlaces*
options are not already set.
+ Moreover, the decimalPlacesRawValue
option is now overwritten by the other decimalPlaces*
options defined in the same option object, if their values are higher.wheelStep
'progressive' mode so that values between ]-1;-1[ are treated specially, by allowing the wheel event to modify the decimal places. The precision used for the step
depends on the number of decimal places used for the rawValue
.
+ Also, numbers between 1 and 9 (included) now use a step of 1
, instead of 10
like before.1.14.0
, instead of latest
, in order to prevent potential incompatibility problems.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.decimalPlaces
option.decimalPlacesRawValue
, decimalPlacesShownOnBlur
and decimalPlacesShownOnFocus
. For more details, read on.scaleDecimalPlaces
to decimalPlacesShownOnBlur
.scaleDivisor
to divisorWhenUnfocused
.scaleSymbol
to symbolWhenUnfocused
.decimalPlacesShownOnBlur.doNotChangeDecimalPlaces
to decimalPlacesShownOnBlur.useDefault
to be coherent with the other decimalPlaces*
options.decimalPlacesOverride
option in favor of explicit decimalPlaces
, decimalPlacesShownOnBlur
and decimalPlacesShownOnFocus
ones.mDec
option is used (which was the equivalent of decimalPlacesOverride
).decimalPlacesRawValue
option that define the precision the user wants to keep (in the rawValue
).decimalPlacesOverride
to temporary change it in set()
._roundValue()
calls: _roundFormattedValueShownOnFocus
, _roundFormattedValueShownOnBlur
and _roundRawValue
. This way we are more explicit in what the code is doing._setRawValue()
so that it only save the given raw value if it's different than the current one (keeping the history table clean)._addGroupSeparators()
, _roundValue()
and _prepareValueForRounding()
to prevent possible wrong typecasts.null
(a toString()
was attempted on the null
value in the _roundValue()
method).inputValueHasADot
in _roundValue()
to better reflect what data it holds, ie. inputValueHasNoDot
.set()
warning messages.NaN
.and
_onFocusOutAndMouseLeave` event handlers.minimumValue
or maximumValue
, and that maximum number of decimal place was used everywhere (except if you also defined decimalPlacesOverride
, decimalPlacesShownOnFocus
or scaleDecimalPlaces
).
+ Now you need to explicitly define the number of decimal places using the decimalPlaces
option.
+ If only decimalPlaces
is defined, then the other decimalPlaces*
options decimalPlacesRawValue
, decimalPlacesShownOnBlur
and decimalPlacesShownOnFocus
are calculated from it.
+ This way, you can now define clearly how many decimal places needs to be shown when focused/unfocused, and as the raw value precision.
+ Note: updating the decimalPlaces
will overwrite any decimalPlaces*
option previously set._maximumVMinAndVMaxDecimalLength()
since we do not set the number of decimal places this way._correctDecimalPlacesOverrideOption()
function since decimalPlacesOverride
is not used anymore._calculateDecimalPlaces()
static method that calculate the decimalPlaces*
option value based on decimalPlaces
and the decimalPlaces*
ones.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._setValueParts()
, set the rawValue
and the formatted element value separately, since they can have different decimal places. For instance we could imagine keeping 3 decimal places for the rawValue
, while only 2 is shown. I then need to make sure we keep that third decimal place information into the rawValue
, instead of trimming it like it was done before.null
scaleSymbol
is a castable to a Number
, and would be added to the formatted value, instead of concatenated.set()
.validate()
so that it throws an error early if scaleDivisor
is wrongly set to 0
._trimLeadingAndTrailingZeros()
so that it correctly handles the null
value._onFocusInAndMouseEnter()
so that the decimalPlacesShownOnFocus
setting is correctly cast to a Number._onFocusOutAndMouseLeave()
so that the null
value is correctly handle. Also fix the error message shown when the rawValue
is not stored as a string.if
one.isFocused
state to false
when calling _addGroupSeparators()
in _onFocusOutAndMouseLeave()
so that it does not rely on the order where this.isFocused
is set back to false
.'euroPos'
).
+ Both the initialization methods new AutoNumeric()
and AutoNumeric.multiple()
support using arrays of options.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.format
and unformat
methods.
+ The latter options in the array will overwrite the previous ones.
+ The array can contains either option objects, or pre-defined option names as a string (ie. 'euroPos'
).AutoNumeric.unformat()
only removes the first instance of settings.digitGroupSeparator
get*
methods to allow passing them a callback function.get*
method result, or the global.get*
method array of result.get*
functions as its first argument, and the current AutoNumeric object as its second._saveValueToPersistentStorage()
method in three : _saveValueToPersistentStorage()
to save the raw value to persistent storage, _getValueFromPersistentStorage()
to retrieve that data, and _removeValueFromPersistentStorage()
to delete it._storageTest
is only done once, and the result is kept in this.sessionStorageAvailable
, and the storage variable name is also generated once and kept in this.rawValueStorageName
.this.storageNamePrefix
attribute. Currently it defaults to 'AUTO_'
;'null'
options to the emptyInputBehavior
setting this.defaultRawValue
variable that store the hard-coded default raw value used during the initialization and reset. { emptyInputBehavior: AutoNumeric.options.emptyInputBehavior.null }
, the user can now explicitly set the AutoNumeric value to null
(using anElement.set(null)
for instance).
+ Additionally, when this option is set, if the AutoNumeric element is emptied, then rawValue
is set to null
.
+ Note: if the current raw value is equal to null
, changing the emptyInputBehavior
option to something different than null
will update the rawValue to ''
.
+ Known limitation : Initializing an AutoNumeric object with the null
value is not allowed since using null
for the initial value means that AutoNumeric needs to use the current html value instead of null
.tagName
can be undefined.form()
method now accepts a true
argument that will force it to discard the current parent form and search for a new one.settings.showWarnings
for most calls to AutoNumericHelper.warning()
, wherever possible.update()
and global.update()
function signatures so that they can accept multiple option objects, the latter overwriting the settings from the former.
+ This allows to fine tune the format settings in one go, and is specially useful when using a predefined option as the 'configuration base', and changing it slightly (ie. anElement.update( AutoNumeric.getPredefinedOptions().French, { digitGroupSeparator: AutoNumeric.options.digitGroupSeparator.noSeparator })
).'autoNumeric:formatted'
event not being correctly sent if the AutoNumeric element was formatted without a keyup
event.
+ The event is now correctly sent when the value is set to empty, or when using unformat()
, unformatLocalized()
and wipe()
, as well as when the user uses the wheel event to change the element value, or the alt + mouse hover
feature, or just hover the element that has a negativeBracketsTypeOnBlur
option set, or on the initial format on load.'autoNumeric:formatted'
was not sent when pasting valid values.AutoNumeric.events
.wheelStep
to 0.01
so that the wheel step is more logical when manipulating a small number.unformatOnSubmit
to true
does not unformat the element on the form' submit
eventselectOnFocus
that allow the user to choose if the value should be selected when the element is focused.caretPositionOnFocus
that allow the user to choose where should be positioned the caret when the element is focused.selectOnFocus
option is true
then the value is selected, otherwise the caret is set at the position defined by the caretPositionOnFocus
option.caretPositionOnFocus
can be 'start'
, 'end'
, 'decimalLeft'
and 'decimalRight'
, and will change where the caret will be positioned when the element get the focus. It can also be null
which means the caret position is not forced._initialCaretPosition()
function.validate()
so that an empty object can be used for the options, since the default settings would then be merged and used.validate()
function signature so that it accepts a third argument, the raw options passed by the user, without them having been merged with the default settings. This is useful for checking conflicting options that could be overwritten by the defaults.validate()
from areSettingsValid()
to make it more explicit._onFocusInAndMouseEnter()
so that it's not reserved only for elements that have their emptyInputBehavior
option set to focus
anymore.focusin
event handler via _onFocusIn()
, which take care of managing the element content selection on focus._correctCaretPositionOnFocusAndSelectOnFocusOptions()
function that manage the caretPositionOnFocus
and selectOnFocus
options in order to prevent any conflict.setElementSelection()
so that element.firstChild
is checked for null
value.negativeBracketsTypeOnBlur
option ('〈,〉', '「,」', '⸤,⸥', '⟦,⟧', '‹,›' and '«,»')unformat()
signature to allow multiple options objects to be passed as arguments.
+ Each more option object overwrite the previous ones.
+ This allows to correctly unformat currencies that have a predefined option as its base, but has been slightly modified (ie. AutoNumeric.unformat('241800,02 €', AutoNumeric.getPredefinedOptions().French, { digitGroupSeparator: AutoNumeric.options.digitGroupSeparator.noSeparator })
, and still get the right result)._checkEmpty()
function into _isElementValueEmptyOrOnlyTheNegativeSign()
and _orderValueCurrencySymbolAndSuffixText()
. Both new functions only do one thing and one thing only, allowing the code to be rewrote in a clearer way._checkEmpty()
function._roundValue()
to make it more legible ; This is done by extracting _roundCloseTo05()
, _prepareValueForRounding()
and _shouldRoundUp()
.while
loop in _stripAllNonNumberCharacters()
init()
so that it allows the user to also pass an array of DOM elements, or a CSS selector as its first argument (cf. issue #388 comments)noSeparatorOnFocus
set to noSeparator
should not remove the decimal character on focus2.0.12
into 4.0.0-beta.*
setValue()
method that allow the user to set any values, without any controls from AutoNumeric.setElementValue
then _setRawValue
with either setValue()
or _setElementAndRawValue()
, so that this call order is respected.setUnformatted()
so that it checks and validates the value given by the user.options.createLocalList()
so that modifying the option will create/delete the local list accordingly.selectDecimal()
so that the decimals are correctly selected when decimalPlacesShownOnFocus
is used.\u202f
in front of %
in the predefined options percentageEU*
(as per the typographic rules).minimumValue
and maximumValue
options are not respected when emptyInputBehavior
is set to 'zero'
autoNumeric
organization, and move the repository to itautoUnformat()
converts digitGroupSeparator
set to .
as the decimal characterAutoNumeric.unformat()
so that 'real' javascript number are always directly returned, without taking into account the options passed (as it was supposed to do previously).AutoNumeric.unformat()
.AutoNumeric.unformat()
unit tests._removeBrackets()
so that we can only remove the brackets, without reordering the negative sign, currency symbol and value according to the settings.settings.trailingNegative
variable, that was used for other things that its names suggests._isTrailingNegative
test to its own function._convertToNumericString()
to make it remove the suffixText
as well._setValueParts()
function.newValue
polluting this
, which allow to explicitly pass the needed information.this.settings.hasFocus
into this.isFocused
.this.settings.strip
variable.'focusin'
to 'focus'
, in order to prepare for the merge of _onFocusInAndMouseEnter()
and _onFocus()
handlers._cleanLeadingTrailingZeros()
so that the trailing zeroes if correctly done, even if leadingZero
is set to keep
._cleanLeadingTrailingZeros()
to _trimLeadingAndTrailingZeros()
._addGroupSeparators()
signature so that the focused state is explicitly passed as a parameter, instead of piggy-backing on the settings object._setTrailingNegativeSignInfo()
function that parse the settings and initialize once the this.isTrailingNegative
property if the negative sign should be trailing for negative values.leftOrAll
parameter from _stripAllNonNumberCharacters()
to a more meaningful stripZeros
._truncateDecimalPlaces()
._skipAlways()
to _processNonPrintableKeysAndShortcuts()
.isNegative()
to make it more efficient.isNegativeWithBrackets()
helper function that tests if the given value is a negative with brackets.styleRules
option that allows to modify the element style based on the raw value, but also to call any callbacks whenever this raw value changeset()
function so that the formatted value is set before setting the rawValue
. That way if a callback invoked by a styleRules
modify the raw value, it'll be set correctly, since the previous set()
call would have already changed the element value via setElementValue()
.allowDecimalPadding
set to never
, then if you delete the decimal places leaving the decimal character, it would not drop that dangling decimal character on focus out.historySize
option that allows to set how many undo states each AutoNumeric object should keep in memory._setRawValue()
function to set the rawValue
; directly setting this.settings.rawValue = 'foo'
is not allowed anymore.set()
function signature by allowing to pass a third parameter to prevent saving the changed state to the history table.keyName
enumeration with the capitalized letters.getElementSelection()
helper function in order to support contenteditable-enabled elements and hidden inputs.arrayTrim()
helper function that trim the start of an array.set()
function to keep logical steps together.autoFormat.autoNumeric
event to the already used autoNumeric:formatted
to keep the names consistent._convertOldOptionsToNewOnes()
function.leadingZero
set to keep
does not keep the leading zeros under Chromenext
version to v4
instead of v3
, just because.options.*
methodsemptyInputBehavior
equal to always
would not reformat the AutoNumeric element correctly if its value is set to the empty string ''
. emptyInputBehavior
equal to zero
would not reformat the AutoNumeric element correctly if its value is set to the empty string ''
. _mergeCurrencySignNegativePositiveSignAndValue()
function that did not manage all negativePositiveSignPlacement
combinations._mergeCurrencySignNegativePositiveSignAndValue()
function.options.*
methods.global.*
featuresset('')
does not respect the emptyInputBehavior
option when it's set to 'always'
createLocalList
option which allow to control whether a local list of AutoNumeric objects should be saved on initializations.global.update()
function to update the settings on a local list.global.clear()
function to be able to force a clear
call.global.nuke()
function to remove
then delete the local list DOM element from the DOM.global.clear()
function signature with the clear()
one.global.addObject()
function that did not update the local list of the added element.global.addObject()
function so that if it add an AutoNumeric object that already has a local list with multiple other AutoNumeric objects, it merges the list.global.removeObject()
function to make it update all the objects local list. Also add special behaviors when an AutoNumeric element removes itself or another one.global.empty()
function to match the removeObject
behavior.init()
method by removing a negation in one of its parameter.init()
method initialization process by preventing creating a local list, then removing it immediately if the user wanted a detached element. Now, the local list is just not created (Using the createLocalList
option set to false
).remove()
method._hasLocalList()
method that tests if the AutoNumeric element has a local list and that it has at least one element in it (itself usually).AutoNumeric.options
object attribute valuesevent.key
instead of event.keyCode
and event.which
since those two attributes are deprecateddotDecimalCharCommaSeparator
, 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
.getLanguages()
to getPredefinedOptions()
.suffixText
options.AutoNumeric.options
object values.selectNumberOnly
value to true
AutoNumeric.languageOptions
object.decimalCharacterAlternative
option enumeration.selectNumberOnly
.AutoNumeric.languageOptions.French
.savedCancellableValue
variable when unneeded.hasFocus
calls and sets.format()
function, since this used the _addGroupSeparators
function that calls the _stripAllNonNumberCharacters
one that extensively uses those.this.settings
object.set()
if the value hasn't changed when calling the 'cancellable' event._setsAlternativeDecimalSeparatorCharacter()
to _setAlternativeDecimalSeparatorCharacter()
.aScale
reference from a test.this.settings
object the following variables : caretFix
, throwInput
, tagList
, originalDecimalPlacesOverride
, originalAllowDecimalPadding
, originalNegativeBracketsTypeOnBlur
, originalDigitGroupSeparator
, originalCurrencySymbol
, originalSuffixText
and aNegRegAutoStrip
._formatValue()
.currencySymbolPlacement
and negativePositiveSignPlacement
valuesmouseleave
event is captured, we do not unformat the element value (with the scale options).'0.00'
on mouseenter
.Alt
contentEditable
-enabled elements_formatDefaultValueOnPageLoad()
method signature.update()
function retrieve the current raw value and one of its test.this.domElement.value
, and use the getElementValue()
to access the element value
or textContent
, and setElementValue()
to set it.getElementSelection()
and setElementSelection()
functions in order to manage non-input DOM elements.getElementValue()
when managing non-input DOM elements.src/main.js
for bundling the library.autoNumeric.js
, which contains the AutoNumeric class,AutoNumericEnum.js
which contains the enumerations used by AutoNumeric, andAutoNumericHelper.js
which contains the AutoNumericHelper class which provides static helper functions.
Extract the allowedTagList
, keyCode
and keyName
into AutoNumericEnum
.
isEmptyString
, isNumberOrArabic
, isFunction
, isElement
, isInputElement
, arabicToLatinNumbers
, triggerEvent
, randomString
, getElementValue
, setElementValue
, cloneObject
, camelize
, text
, setText
and filterOut
functions to the helper functions.preparePastedText
, runCallbacksFoundInTheSettingsObject
, maximumVMinAndVMaxDecimalLength
, stripAllNonNumberCharacters
, toggleNegativeBracket
, convertToNumericString
, toLocale
, modifyNegativeSignAndDecimalCharacterForRawValue
, modifyNegativeSignAndDecimalCharacterForFormattedValue
, checkEmpty
, addGroupSeparators
, truncateZeros
, roundValue
, truncateDecimal
, checkIfInRangeWithOverrideOption
functions into the AutoNumeric object.character()
method to take into account the quirks of some obsolete browsers.getCurrentElement()
function since we now only need to access the this.domElement
property.AutoNumericHolder
class and the getAutoNumericHolder()
function since we are now using the AutoNumeric class as the 'property holder'._setArgumentsValues()
method).serializeSpaces
option that allows the user to defines how the serialize function will managed the spaces, either by converting them to '%20'
, or to the '+'
string, the latter now being the default.noEventListeners
option that allows the user to initialize an AutoNumeric <input>
element without adding any AutoNumeric event listeners.readOnly
option to the settings that allow the <input>
element to be set to read-only on initialization..global.*
functions).isPristine()
method to test if an AutoNumeric-managed element value
/textContent
has been changed since its initialization.unset
to unformat
.reSet
to reformat
.unformatLocalized()
function to unformat the element value while using the outputFormat
setting.clear()
method to empty the element value.nuke()
method to remove the DOM element from the DOM tree..global.has()
method to check if the given AutoNumeric object (or DOM element) is in the local AutoNumeric element list..global.addObject()
method that adds an existing AutoNumeric object (or DOM element) to the local AutoNumeric element list..global.removeObject()
method that removes the given AutoNumeric object (or DOM element) from the local AutoNumeric element list..global.empty()
method to remove all elements from the shared list..global.elements()
method to retrieve all the AutoNumeric object that share the same local list..global.getList()
method to retrieve the local AutoNumeric element list.version()
method to output the current AutoNumeric version (for debug purpose).set()
method so that the rawValue
is updated when the value is set to ''
.setUnformatted()
method to set the value given value directly as the DOM element value, without formatting it beforehand.get()
method to the renamed getNumericString()
which bares more meaning.getFormatted()
method to retrieve the current formatted value of the AutoNumeric element as a string.getNumber()
method that returns the element unformatted value as a real Javascript number.getLocalized()
method that returns the unformatted value, but following the outputFormat
setting.unformatLocalized()
method that unformats the element value by removing the formatting and keeping only the localized unformatted value in the element.selectNumber()
method that select only the numbers in the formatted element content, leaving out the currency symbol, whatever the value of the selectNumberOnly
option.selectInteger()
method that select only the integer part in the formatted element content, whatever the value of the selectNumberOnly
option.selectDecimal()
method that select only the decimal part in the formatted element content, whatever the value of selectNumberOnly
.node()
method that returns the DOM element reference of the autoNumeric-managed element.parent()
method that returns the DOM element reference of the parent node of the autoNumeric-managed element.detach()
method that detach the current AutoNumeric element from the shared local 'init' list.attach()
method that attach the given AutoNumeric element to the shared local 'init' list.formatOther()
method that format and return the given value, or set the formatted value into the given DOM element if one is passed as an argument.unformatOther()
method that unformat and return the raw numeric string corresponding to the given value, or directly set the unformatted value into the given DOM element if one is passed as an argument.init()
method that allows to use the current AutoNumeric element settings to initialize the DOM element given as a parameter. This effectively link the two AutoNumeric element by making them share the same local AutoNumeric element list.form()
method that return a reference to the parent formNumericString()
method that returns a string in standard URL-encoded notation with the form input values being unformatted.formFormatted()
method that returns a string in standard URL-encoded notation with the form input values being formatted.formLocalized()
method that returns a string in standard URL-encoded notation with the form input values, with localized values.formArrayNumericString()
method that returns an array containing an object for each form <input>
element.formArrayFormatted()
method that returns an array containing an object for each form <input>
element, with the value formatted.formArrayLocalized()
method that returns an array containing an object for each form <input>
element, with the value localized.formJsonNumericString()
method that returns a JSON string containing an object representing the form input values.formJsonFormatted()
method that returns a JSON string containing an object representing the form input values, with the value formatted.formJsonLocalized()
method that returns a JSON string containing an object representing the form input values, with the value localized.formUnformat()
method that unformat all the autoNumeric-managed elements that are a child of the parent formUnformatLocalized()
method that unformat all the autoNumeric-managed elements that are a child of the parent formReformat()
method that reformat all the autoNumeric-managed elements that are a child of the parent formSubmitNumericString()
method that convert the input values to numeric strings, submit the form, then reformat those back.formSubmitFormatted()
method that submit the form with the current formatted values.formSubmitLocalized()
method that convert the input values to localized strings, submit the form, then reformat those back.formSubmitArrayNumericString()
method that generate an array of numeric strings from the <input>
elements, and pass it to the given callback.formSubmitArrayFormatted()
method that generate an array of the current formatted values from the <input>
elements, and pass it to the given callback.formSubmitArrayLocalized()
method that generate an array of localized strings from the <input>
elements, and pass it to the given callback.formSubmitJsonNumericString()
method that generate a JSON string with the numeric strings values from the <input>
elements, and pass it to the given callback.formSubmitJsonFormatted()
method that generate a JSON string with the current formatted values from the <input>
elements, and pass it to the given callback.formSubmitJsonLocalized()
method that generate a JSON string with the localized strings values from the <input>
elements, and pass it to the given callback.test()
method that if the given domElement is already managed by AutoNumeric (if it has been initialized on the current page)._mergeSettings()
and _cloneAndMergeSettings()
to do what they are named about.format()
method so that it formats the given number (or numeric string) with the given options, and returns the formatted value as a string.formatAndSet()
method that format the given DOM element value, and set the resulting value back as the element value.unformat()
method so that it unformats the given formatted string with the given options, and returns a numeric string.unformatAndSet()
method that unformat the given DOM element value, and set the resulting value back as the element value.localize()
method that unformat and localize the given formatted string with the given options, and returns a numeric string.isManagedByAutoNumeric()
method that returns true
is the given DOM element has an AutoNumeric object that manages it.getAutoNumericElement()
method that returns the AutoNumeric object that manages the given DOM element.french()
, northAmerican()
, british()
, swiss()
, japanese()
, spanish()
and chinese()
methods that update the settings to use the named pre-defined language options.setReal
from some functions.this.settings
directly).isNan()
on non-number elements like strings.this.isFocused
variable.getElementValue()
function to retrieve the element value
or textContent
(depending if the element in an <input>
or another tag), which allow AutoNumeric to perform some operations on non-input elements too. This is the first changes needed for the goal of managing the non-input tags with contentEditable
with AutoNumeric.getElementValue()
function as well in order to be able to set the value
or textContent
transparently where needed._updateAutoNumericHolderProperties()
to _updateInternalProperties()
._checkElement()
method). This simplify the process by calling the new _isElementTagSupported()
, _isInputElement()
and _isInputTypeSupported()
functions which respect the separation of concerns._formatDefaultValueOnPageLoad()
method now accepts a 'forced' initial value instead of the default one.set()
methods, since those cannot change once AutoNumeric has been initialized, simplifying the code.settings.formatOnPageLoad
inside the formatDefaultValueOnPageLoad()
function that is only called if settings.formatOnPageLoad
is already set).getInitialSettings()
method to _setSettings()
._getSignPosition()
function._serialize()
function that take care of serializing the form data into multiple output as needed, which is called by the _serializeNumericString()
, _serializeFormatted()
,_serializeLocalized()
, _serializeNumericStringArray()
, _serializeFormattedArray()
and _serializeLocalizedArray()
methods.AutoNumeric.defaultSettings
.AutoNumeric.options
object that gives access to all the possible options values, with a semantic name (handy for IDE autocompletion).AutoNumeric.languageOptions
object.AutoNumeric.multiple()
function that allows to initialize numerous AutoNumeric object (on numerous DOM elements) in one call (and possibly pass multiple values that will be mapped to each DOM element).<input>
tags.noEventListeners
or readOnly
options.serializeSpaces
, noEventListeners
and readOnly
options.rawValue
was correctly set when using getSettings()
..global.*
methods.AutoNumeric.multiple()
methods.selectDecimal
, selectInteger
, reformat
, unformat
and unformatLocalized
methods..form*
methods.babel-plugin-transform-object-assign
dev dependency in order to be able to use Object.assign()
in the ES6 source.modifyValueOnWheel
that allow the user to use mouse wheel to increment/decrement the element valuewheelStep
option allows to either define a fixed step (ie. 1000
), or a progressive one calculated based on the current element valueEscape
key (if no changes have been made to the element value, otherwise this will cancel those changes if the isCancellable
is set to true
)Tab
key, when selectNumberOnly
is set to true
_selectOnlyNumbers()
function that extract that behavior for re-use._select()
function that select the whole element content, while respecting the selectNumberOnly
option._defaultSelectAll()
function that select the whole element content, including all characters.setElementSelection()
calls to simplify them with the ability to use one argument instead of two when the start
and end
position are the same.next
to master
.
+ This fix the issue #465 "Unable to get property 'getData' of undefined or null reference" on paste in IE11AutoNumeric.unformat()
only removes the first instance of settings.digitGroupSeparator
from next
to master
.maximumValue
and minimumValue
options are not taken into account on AndroiddecimalCharacterAlternative
is not taken into account on Android ChromekeyCode.AndroidDefault
onPaste
handler throwing an error for uninitialized variablesarabicToLatinNumbers()
function to return more quickly if no arabic numbers are foundautoNumeric
organization, and move the repository to itnpm install
for version 2.0.4 does not work on Windows machinesdist
files in the last publish to npmjs were not rebuilt with the fixes pushed to 2.0.1dist
files are not included when publishing to npmjsemptyInputBehavior
value focus
dist
files are not included when publishing to npmjs2.0.0
, enjoy! (¬‿¬) showPositiveSign
option to display the positive sign wherever neededlanguageOption
objectnpm
to yarn
set
with Arabic and Persian numbers (ie. aNInput.autoNumeric('set', '١٠٢٣٤٥٦٧.٨٩');
)value
attributenegativePositiveSignPlacement
option can be ignored in some casesget
returns '0'
when the input is empty even if emptyInputBehavior
is not equal to 'zero'
Tab
key, the value is not always selected ','
, '.'
, '٬'
, '˙'
, "'"
, ' '
, '\u2009'
, '\u202f'
, '\u00a0'
and ''
'.'
, ','
, '·'
, '⎖'
and '٫'
this.selection
can be uninitialized if you focus on an input via the Tab
key.keyName
object that list the key values as defined is the KeyboardEvent Key_Values.key()
function to keyCodeNumber()
._updateFieldProperties()
into _updateAutoNumericHolderProperties()
and _updateAutoNumericHolderEventKeycode()
._updateAutoNumericHolderProperties()
only update the value and selection in each event handler, and resets the 'processed' and 'formatted' states._updateAutoNumericHolderEventKeycode()
is called only once on keypress
, and set the event keyCode into the AutoNumericHolder object.this.ctrlKey
, this.cmdKey
and this.shiftKey
three times on each key stroke.this.kdCode
into this.eventKeyCode
, and use that variable globally in the AutoNumericHolder object._normalizeParts()
so that a '0' entered via the numpad is managed as well.keyCode
values._processCharacterInsertion()
so that it take the event as an argument, and therefore can directly use e.key
._formatValue()
tests.Old name | ++ | New name | +
---|---|---|
autoCheck() | +-> | +checkIfInRangeWithOverrideOption() | +
autoRound() | +-> | +roundValue() | +
autoGroup() | +-> | +addGroupSeparators() | +
fixNumber() | +-> | +modifyNegativeSignAndDecimalCharacterForRawValue() | +
presentNumber() | +-> | +modifyNegativeSignAndDecimalCharacterForFormattedValue() | +
negativeBracket() | +-> | +toggleNegativeBracket() | +
autoGet() | +-> | +getCurrentElement() | +
getHolder() | +-> | +getAutoNumericHolder() | +
autoSave() | +-> | +saveValueToPersistentStorage() | +
_setPosition() | +-> | +_setCaretPosition() | +
_signPosition() | +-> | +_getSignPosition() | +
_formatQuick() | +-> | +_formatValue() | +
validate()
function to show a warning when decimalPlacesOverride
is greater than decimalPlacesShownOnFocus
.onInvalidPaste
option that can accept the error
, ignore
, clamp
, truncate
and replace
value.autoStrip()
to stripAllNonNumberCharacters()
.setElementSelection()
function so that it can accept only one caret position.failOnUnknownOption
option which allows autoNumeric to strictly analyse the options passed, and fails if an unknown options is used in the settings object.leadingZero
option deny
does not function correctly and deletes some of the zero to the right of the caretcurrencySymbolPlacement
set as p
(prefix)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 | +
convertOldOptionsToNewOnes()
function that automatically convert old options to new ones, to ease the evolution to v2.*.typings.d.ts
accordinglyREADME.md
accordinglyisNumber()
helper function to test if a value is a number, or a string representing a number.isInt()
helper function to test if a value is a 'real' integer.decimalPlaces()
so that it always return the number of decimal places (ie. 0
instead of null
if there is none). key()
helper function to retrieve an event keyCode.runCallbacks()
into runCallbacksFoundInTheSettingsObject()
.decLength()
function, as well as removing unnecessary code before each call to this function.decLength()
to maximumVMinAndVMaxDecimalLength()
.autoCode()
call hierarchy.autoCode()
into getInitialSettings()
.autoGroup()
to use switch statements.dPos
was used to make it more understandable.keepOriginalSettings
into keepAnOriginalSettingsCopy()
.autoSave()
so that it directly uses the element as an argument, instead of a jQuery reference.init()
function to _updateFieldProperties()
.processAlways()
into _processCharacterDeletion()
, and simplify it so that if does not do two things at the same time.processKeypress()
into _processCharacterInsertion()
, and simplify it so that if does not do two things at the same time._formatQuick()
.$this.val()
to e.target.value
).getHolder()
calls in the event listeners.change
event when used and the value has been changed.onBlur
event listener, allowing us to trigger change
events as needed.getInitialSettings()
length by a great deal, making it easier to read and understand.getInitialSettings()
functions now calls the calculateVMinAndVMaxIntegerSizes()
, correctMDecOption()
, setsAlternativeDecimalSeparatorCharacter()
, cachesUsualRegularExpressions()
and transformOptionsValuesToDefaultTypes()
functions.update()
code into getInitialSettings()
, which allows to remove the autoCode()
calls from the AutoNumericHolder constructor and the _updateFieldProperties()
function.getSettings()
.validate()
test on the mDec
option to allow for a positive integer too.autoFormat()
function to format numbers represented as a string.autoFormat()
tests and check for the value validity.sendCustomEvent()
function and replace it by the triggerEvent()
one (and remove createCustomEvent()
as well).autoUnFormat()
tests and check for the value validity.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.parseInt
function.clean:build
npm script so that it does not try to remove an inexistant folder.localOutput
setting to outputType
, and add an option 'number' that makes getLocalized
always return a Number, instead of a string.get
function so that it always returns a valid Number or string representing a number that Javascript can interpret.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).pNeg
default value based on the aSign
and pSign
values. This leads to better user experience when setting a currency symbol without setting pNeg
.debug
option now only affects the warning messages (used for non-critical errors).validate()
method that checks if the given options object is valid.init
function code to check for critical error first, before doing other calculus.areSettingsValid()
method that return true if the options object is valid.isBoolean
, isNull
, isTrueOrFalseString
, isObject
, isEmptyObj
, hasDecimals
, decimalsPlaces
.warning()
method that output warning message to the console.originalSettings
to keepOriginalSettings
to better convey what this function is doing.ctrl-v
// issue #251 special thanks to @rhyek$.extend
defaults // thanks gayan85 issue #229get
methodinput
eventunSetOnSubmit
to unformat input on the submit eventdebug
to turn on and off error being thrownsNumber
option that selects only numbers ctr & a keys thanks ZayteranDefault
to help ASP.NETR postback errorswEmpty
optioninit
&& set
methodsset
, getString
& getArray
methodsnBracket
functionupdate
method when it is called during the onfocus
eventgetString
& getArray
methods when multiple inputs share the same name - Thanks Retromaxctrl + v
paste event to properly round .
None!
Info
+The jQuery dependencies has been removed in v4.0.0
.
Contributors and pull requests are welcome. Feel free to contact us for any questions.
+For more detailed information about how to contribute, please check the rest of this page.
+In a nutshell:
+git clone -b next https://github.com/autoNumeric/autoNumeric.git && cd autoNumeric && yarn install
yarn lint && yarn build && yarn test
yarn lintfix
Again, be sure to check the following guidelines for more details.
+Also, feel free to follow our RSS feeds on master and next to keep up with the latest commits.
+Every contribution are welcomed, whatever their sizes.
+If you want to contribute to a dynamic and welcoming open-source project, be sure to check our easy-to-start-with junior jobs, either by checking the issues for the tag Junior jobs, or by searching for the //TODO
and //FIXME
strings directly in the source (there are plenty awaiting for you right now!).
Happy coding :>
+git clone -b next https://github.com/autoNumeric/autoNumeric.git
+# or the following if you are authentified on Github:
+# `git clone -b next git@github.com:autoNumeric/autoNumeric.git`
+
Note
+You can use either npm
or yarn
for running the install/build scripts. We'll use yarn
in the following examples.
First things first, in order to be able to compile the ES6 source to something that can be interpreted by the browsers, and get the tools (linter, test runners, etc.) used by the developers, you need to install them by doing : +
+Hint
+You need to have yarn
installed before executing this command.
You can install yarn
globally by doing npm install -g yarn
as root.
Once you made your changes, you can build the library with : +
+This will generate theautoNumeric.js
and autoNumeric.min.js
files in the dist
folder, that you'll then be able to use in the browsers.
+If you want to clean the generated .js
and .min.js
files as well as development specific ones like coverage and log files, use :
+
Warning
+Do not use yarn clean
as it's a different command entirely.
We strive to keep the tests green at all times. Hence whenever you change the source, be sure to:
+eslint
does not return any errors regarding the coding style.Warning
+Pull requests that turns the tests red , or that do not provide new tests for new features will not be accepted.
Tests must always be green before pushing. Any commit that make the tests fails will be ignored.
To run the tests, you have multiple options:
+
# Run unit testing as well as end-to-end testing
+yarn test
+
+# Run unit testing only
+yarn test:unit
+
+# Run end-to-end testing only
+yarn test:e2e
+
+# Run unit testing only...
+yarn test:unitp # ...with PhantomJS only
+yarn test:unitf # ...with Firefox only
+yarn test:unitc # ...with Chrome only
+
Behind the scene, all unit and end-to-end tests are written with Jasmine.
Karma is used to run the unit tests, while Webdriver.io is used to run end-to-end tests.
Linting allow us to keep a coherent code style in all the source files.
In order to check that everything is well formatted, run eslint with:
+
# Use the path of the faulty file to fix only this particular file:
+./node_modules/eslint/bin/eslint.js --fix src/AutoNumeric.js
+
+# Or try to fix all errors in all files once with
+yarn lintfix
+
Every changes that you pushed in its own branch in your personal AutoNumeric repository copy should be based on the latest version of the next
branch (the development branch).
When you create a pull request, make sure to push against the next
branch.
Please try to break down your pull requests and commits into small and manageable entities, in order:
+Additionally, your commits must not contain any generated files (ie. files built in the /dist/
directory, or logs).
Important changes regarding the generated dist
files
Since the version 4.1.3
, the generated dist
files (ie. autoNumeric.js
and autoNumeric.min.js
) are not pushed into the repository anymore.
However, all tagged commits are now automatically built and published on npm.
+This means if you want to download the minified library directly, you need to use npm to install it (yarn add autonumeric
or npm install autonumeric
).
1.9.*
/2.*
to version 4.*
Attention!
+Version 4
has seen a lots of improvements and new features, but also introduce breaking changes if you are trying to use it with an old v1.9
or v2
configuration.
Initialization of an AutoNumeric object has changed a bit.
+Since AutoNumeric is now an ES6 module, AutoNumeric
being the name of the class
, and since the jQuery dependency has been dropped, you now longer need to first select the DOM element with jQuery, then call the $(yourElement).autoNumeric('init', { options })
method.
Now, you only need to instantiate an AutoNumeric
object using new AutoNumeric(yourElement, { options })
(or if you do not already have a reference to the DOM element, use new AutoNumeric('myCSSSelector', { options })
).
<= v2 (Before) |
+v4 (After) |
+
---|---|
$('.myInput').autoNumeric('init', { options }); |
+If you want to initialize only one element: new AutoNumeric('.myInput', { options }); |
+
+ | If you want to initialize multiple elements: AutoNumeric.multiple('.myCssClass > input', { options }); |
+
Deprecation warning
+The old option names have changed and are now deprecated, in favor of the new ones.
+To help you switch to the new names, detailed warning messages are displayed in the console if an old option name is detected.
+mDec
option changes
Do note that the option mDec
(or its new name decimalPlacesOverride
if you used v2
) is no longer used.
If you want to specify the number of decimals, instead of relying on the maximum number of decimal places in minimumValue
or maximumValue
like before, you can now set decimalPlaces
to set it globally.
If you wish, you can also specify a different number of decimal places for the formatted value (with decimalPlacesShownOnFocus
and decimalPlacesShownOnFocus
) or the rawValue
(with decimalPlacesRawValue
).
The following table shows the equilavence between pre and post v4
version for option names:
<= v2 (Before) |
+v4 (After) |
+
---|---|
aSep |
+digitGroupSeparator |
+
nSep |
+showOnlyNumbersOnFocus |
+
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 |
+decimalPlacesShownOnBlur |
+
aStor |
+saveValueToSessionStorage |
+
mRound |
+roundingMethod |
+
aPad |
+allowDecimalPadding |
+
nBracket |
+negativeBracketsTypeOnBlur |
+
wEmpty |
+emptyInputBehavior |
+
lZero |
+leadingZero |
+
aForm |
+formatOnPageLoad |
+
sNumber |
+selectNumberOnly |
+
anDefault |
+defaultValueOverride |
+
unSetOnSubmit |
+unformatOnSubmit |
+
outputType |
+outputFormat |
+
debug |
+showWarnings |
+
If you want more detail about the AutoNumeric options, feel free to browse the AutoNumeric options source code which has detailed comment for each one.
+Do note that you can check out the new options on the official website here.
+Moreover, since we are now using an AutoNumeric
object, we can now directly call its methods (and chain them if needed).
+In the following table, the anElement
variable is created using const anElement = new AutoNumeric('someSelector', { options })
.
The methods are now called like so:
+<= v2 (Before) |
+v4 (After) |
+
---|---|
$(someSelector).autoFormat('1234.56', { options }); |
+AutoNumeric.format(1234.56, { options }); |
+
$(someSelector).autoUnFormat('1.234,56 €', { options }); |
+AutoNumeric.unformat('1.234,56 €', { options }); |
+
$(someSelector).autoValidate({ options }); |
+AutoNumeric.validate({ options }) |
+
$.fn.autoNumeric.defaults |
+AutoNumeric.getDefaultConfig() |
+
$(someSelector).autoNumeric("destroy"); |
+anElement.remove(); |
+
$(someSelector).autoNumeric('get'); |
+anElement.getNumericString(); |
+
$(someSelector).autoNumeric('getArray'); |
+anElement.formArrayNumericString(); |
+
$(someSelector).autoNumeric('getFormatted'); |
+anElement.getFormatted(); |
+
$(someSelector).autoNumeric('getLocalized'); |
+anElement.getLocalized(); |
+
$(someSelector).autoNumeric('getNumber'); |
+anElement.getNumber(); |
+
$(someSelector).autoNumeric('getString'); |
+anElement.formNumericString(); |
+
$.fn.autoNumeric.lang |
+AutoNumeric.getPredefinedOptions() |
+
$(someSelector).autoNumeric('reSet'); |
+anElement.reformat(); |
+
$(someSelector).autoNumeric('set', '12345.67'); |
+anElement.set(12345.67); |
+
$(someSelector).autoNumeric('unSet'); |
+anElement.unformat(); |
+
$(someSelector).autoNumeric("update", { options }); |
+anElement.update({ options }); |
+
$(someSelector).autoNumeric("wipe"); |
+anElement.wipe(); |
+
Check the methods documentation to see how some of those functions signatures changed.
+If you encounter any problem upgrading to v4
, feel free to contacts us on our Gitter channel or on IRC on Libera Chat #autoNumeric
!
Please check the contact page for more information.
+ + + + + + + + + + + + + +Multiple configuration options allows you to customize precisely how a form <input>
element 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.
+Want to know more? Check out the examples.
+Below are listed in alphabetical order the options that you can pass an AutoNumeric element, in order to make it change its behavior or formatting specifications.
+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 (up to the number of decimal places from the decimalPlaces variable). If set to an integer, padding will use that number for adding the zeros. If set to true it will always pad the decimal places with zeroes, and never if set to false . |
+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' |
+
modifyValueOnUpDownArrow |
+Determine if the element value can be incremented / decremented with the up and down arrow keys. The keys behavior is modified with the upDownStep option. |
+true |
+
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 |
+
negativePositiveSignBehavior |
+Defines if the negative sign should be toggled when hitting the negative or positive key multiple times | +false |
+
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 (i.e. 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 dependent 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 |
+
upDownStep |
+Used in conjonction with the modifyValueOnUpDownArrow option, this allows to either define a fixed step (i.e. 1000 ), or a progressive one that is calculated based on the size of the current value |
+'1' |
+
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 allows to either define a fixed step (i.e. 1000 ), or a progressive one that is calculated based on the size of the current value |
+'progressive' |
+
If you want to see AutoNumeric in action and try it yourself, you can either play with the field on the AutoNumeric homepage, or check the live demo.
+You can also take a look at the predefined options examples (Predefined language options, Predefined common options, Predefined common monetary options, Predefined percentage options and Predefined style rules).
+Finally, you can use the configuration generator tool to generate your configuration options objects, while being able to see with a live preview the effect of each chosen options.
+Alternatively, you can also check the vue-autonumeric demo.
+ + + + + + + + + + + + + +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 expressionTip
+You can also set if the events triggered by the AutoNumeric elements, custom or native, should:
+eventBubbles
) oreventIsCancelable
).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:formatted'
The 'autoNumeric:formatted'
event has a payload that contains the following detail
attribute:
+
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
+}
+
function onFormattedEvent(event) {
+ if (!event.detail.isPristine) {
+ console.log(`The element value has been changed from ${event.detail.oldValue} to ${event.detail.newValue}.`);
+ }
+}
+
'autoNumeric:rawValueModified'
The 'autoNumeric:rawValueModified'
event has a payload that contains the following detail
attribute:
+
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
+ },
+ // ...
+}
+
'autoNumeric:initialized'
The 'autoNumeric:initialized'
event has a payload that contains the following detail
attribute:
+
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
+ },
+ // ...
+}
+
'autoNumeric:invalidFormula'
The 'autoNumeric:invalidFormula'
event has a payload that contains the following detail
attribute:
+
const theCustomEvent = {
+ detail : {
+ formula : '22+35 - (44', // The invalid formula
+ aNElement: theAutoNumericObject, // The AutoNumeric object emitting this event
+ },
+ // ...
+}
+
'autoNumeric:validFormula'
The 'autoNumeric:validFormula'
event has a payload that contains the following detail
attribute:
+
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
+Below 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:
'keydown'
'autoNumeric:minExceeded'
or 'autoNumeric:maxExceeded'
only if there was a range problem'keypress'
(this is deprecated and will be removed soon)'input'
'keyup'
'autoNumeric:formatted'
when all the formatting is done'autoNumeric:rawValueModified'
when the rawValue
is modifiedNote
+Please check 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:
'keydown'
'keyup'
'autoNumeric:formatted'
'autoNumeric:rawValueModified'
If Delete
or Backspace
is entered, the following events are sent:
'keydown'
'input'
'keyup'
'autoNumeric:formatted'
'autoNumeric:rawValueModified'
If Enter
is entered and the value has not changed, the following events are sent:
'keydown'
'keypress'
'keyup'
'autoNumeric:formatted'
'autoNumeric:rawValueModified'
If Enter
is entered and the value has been changed, the following events are sent:
'keydown'
'keypress'
'change'
'keyup'
'autoNumeric:formatted'
'autoNumeric:rawValueModified'
When a paste
is done with the mouse, the following events are sent:
'input'
'keydown'
'input'
'keyup'
'keyup'
'autoNumeric:formatted'
'autoNumeric:rawValueModified'
When a paste
is done with the keyboard shortcut (ie. ctrl+v
), the following events are sent:
'keydown'
'keydown'
'input'
'keyup'
'keyup'
'autoNumeric:formatted'
'autoNumeric:rawValueModified'
Ever wished while filling in a form that you could quickly calculate basic math operations?
Well, AutoNumeric provides a quick way to enter and evaluate simple math expressions directly into the element!
Use case
+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
Warning
+By default, this behavior is disabled.
Check here on how to enable it.
If you want to enable the math expression parsing, you need to set the formulaMode
option to true
:
+
If you want to cancel the math expression edition and exit the formula mode, hit the Escape
key at any time.
+This will revert any changes made to the input content to the previous formatted value.
When the formula mode is enabled, you can enter the formula mode just by:
+=
character Enter
keyIf your math formula is valid, then its result will be set()
and you'll automatically exit 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 )
.
Math precedence
+Parentheses and operators precedence are respected as expected
+This allows for evaluating the following math expressions examples without problems:
+8 * -12.46
22* (10 - 2)/1.5- -0.5
(4+1) * 2 - (104587.23 * 8 - (-7))
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.
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/autonumeric@4.8.1"></script>
+<!-- ...or -->
+<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/4.8.1/autoNumeric.min.js"></script>
+<!-- ...or -->
+<script src="https://unpkg.com/autonumeric"></script>
+<!-- ...or any other CDN. -->
+
If you want to use AutoNumeric in your code, you can import the src/AutoNumeric.js
file as an ES6 module using:
+
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();
+
You're done!
+See the available predefined language list here.
+Tip
+An AutoNumeric object can be initialized in various ways, check those out here.
+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:
+
Doing this will allow your project Webpack configuration to compile it correctly (and use tree shaking as needed).
+ + + + + + + + + + + + + +An AutoNumeric object can be initialized in various ways.
+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
+
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 the QuerySelector
Javascript function, 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
.
If you know you want to initialize multiple elements in one call, you must then use the static AutoNumeric.multiple()
function:
+
[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']);
+
Tip
+You can pass multiple different values to the selected inputs, using an Array
. Those values will be mapped one-to-one in the order the elements are found.
If you want to select multiple elements via a CSS selector, then you must use the multiple
function as well as above.
Under the hood the QuerySelectorAll
Javascript function 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
+
Tip
+The AutoNumeric.multiple()
function will always return an Array
, even if there is only one element selected.
Note
+Using an array of option objects and/or pre-defined names will always merge those settings together. The resulting settings
objet will then be applied to all the selected elements; they will share the exact same settings.
AutoNumeric treats <form>
elements differently; 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 });
+
You can install AutoNumeric with your preferred dependency manager:
+set
, get
, format
and unformat
The main functions for using AutoNumeric are set()
which allows you to set the numeric raw value of an input (AutoNumeric will then automatically format it as per the options you used), and get*
which allows you to retrieve the value of an input, either formatted or by getting the raw value directly.
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 }); |
+
Method | +Description | +Call example | +
---|---|---|
getNumericString |
+Return the unformatted number as a string | +anElement.getNumericString(); |
+
get |
+Alias for the .getNumericString() method ( |
+anElement.get(); |
+
getFormatted |
+Return the formatted string | +anElement.getFormatted(); |
+
getNumber |
+Return the unformatted number as a number (Number.MAX_SAFE_INTEGER , you will encounter problems if you try to retrieve it as a number and not as 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); |
+
Method | +Description | +Call example | +
---|---|---|
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); |
+
Method | +Description | +Call example | +
---|---|---|
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); |
+
isPristine |
+Return true if the current value is the same as when the element first got initialized (not set() ) |
+anElement.isPristine(); |
+
Tip
+Most of those functions can be chained together, if needed.
+get*
methodsAll get*
methods can accept a callback function as its argument (those methods being get
, getNumericString
, getFormatted
, getNumber
and getLocalized
; see here).
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);
+
Info
+The callback function behavior is slightly different when called on multiple elements via global.get*
methods.
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(); |
+
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); |
+
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. 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. 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 }); |
+
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.
+Important
+This works only on elements that can be managed by AutoNumeric.
You can check the list of supported elements here.
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'); |
+
This local 'init' list can be used to perform global operations on all those AutoNumeric elements, with one function call.
Example
+The function names are the same as the ones that are used on a single AutoNumeric element.
+For instance instead of calling anElement.set(42)
on a single element, you must call the function by prefixing .global
before the method name like so: 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();
+
Do note that the .global.get*()
functions return an array of results, with one value for each AutoNumeric element in the linked list
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
+
global.get*
methodsLike 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);
+
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.
Form functions can be divided in two categories:
+The functions below makes retrieving and preparing the form values easy. Those values can be formatted or not, and in any format you would want (Array
, JSON, string, etc.).
You can then decide how and when to send those form values to the server.
+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 | +anElement.formUnformat(); |
+
formUnformatLocalized |
+Unformat all the AutoNumeric-managed elements that are a child to the parent | +anElement.formUnformatLocalized(); |
+
formReformat |
+Reformat all the AutoNumeric-managed elements that are a child to the parent | +anElement.formReformat(); |
+
Submitting the form values to the server can be done with a single AutoNumeric function call. +Moreover, the functions below may take a callback, giving you more control on what to do when submitting data to the server.
+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); |
+
Most of those instantiated functions can be chained which allow to be less verbose and more concise.
+anElement.french()
+ .set(42)
+ .update({ options })
+ .formSubmitJsonNumericString(callback)
+ .clear();
+
anElement.global.set(72)
+ .global.clear()
+ .set(25)
+ .global.getNumericString();
+
AutoNumeric also provide static functions on the AutoNumeric class. You can check those out in the next chapter.
+ + + + + + + + + + + + + +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, which is declared as an ES6 Module.
First, you need to get a reference to the AutoNumeric module that you need to import: +
+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.
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
.
AutoNumeric can be used in two ways;
+<input>
elements or on contenteditable
-enabled elements making them reactive (in a read/write mode), orcontenteditable
attribute set to true
, essentially acting as a format-once-and-forget read only mode.<input>
elementsWhen 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<input type='text' value="1234.56">
+<input type='tel' value="1234.56">
+<input type='hidden' value="1234.56">
+<input value="1234.56">
+
Caveat
+The number
type is not supported simply because AutoNumeric formats numbers as strings (ie. '123.456.789,00 €'
) that this input type does not allow.
contenteditable
-enabled elementsAny element in the following allowedTagList
1 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 and manage the user inputs.
Given the following html code... +
+you can initialize this<p>
element with AutoNumeric:
+
+...and it will act exactly like an <input>
element controlled by AutoNumeric.
+You can use AutoNumeric to format a DOM element value once on load.
+This means it will then not react to any user interaction nor changes to it's value or formatting.
The following elements are accepted:
+Allowed tags list
+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.
The allowedTagList
contains the following HTML elements : 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
↩
Sometimes you do not want to have to configure every single aspect of your format using the configuration options, specially if it's a common one.
Hence, we provide multiple default options for the most common currencies and number formats.
AutoNumeric provides predefined language options to format currencies.
+You can set the pre-defined language option like so:
+
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!
+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: +
+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 rules are available so you do not have to create them:
+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 });
+
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 });
+
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 });
+
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 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.
Important
+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 variations | +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 for how to use those callback variations: +
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(); } },
+ ],
+ },
+}
+
Projects have been created to integrate AutoNumeric in existing frameworks, so that the library could be used easily in components.
+Info
+Some of the following projects may lag with the latest AutoNumeric version, or even be incomplete.
+For integration into Javascript frameworks, you can use:
+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.
+ + + + + + + + + + + + + +noEventListeners
Using the noEventListeners
option allows AutoNumeric to apply formatting 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 with setting up event listeners, but removing them in the same call
+anElement = new AutoNumeric(domElement, 12345.789, { options }).remove(); // This is the default existing way of doing that...
+
+// Initialize without setting up any event listeners by directly passing the special option `noEventListeners` to prevent the initial creation of those event listeners
+anElement = new AutoNumeric(domElement, 12345.789, { noEventListeners: true });
+
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:
+
For more detail on how to use each options, please take a look at the detailed comments in the source code for the AutoNumeric.defaultSettings
object.
Without having to initialize any AutoNumeric object, you can directly use the static AutoNumeric
class functions.
Info
+Some of those functions can be used in Web Workers.
+Method | +Description | +Call example | +
---|---|---|
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 |
+
Method | +Description | +Call example | +
---|---|---|
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 }); |
+
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 }); |
+
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) |
+
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); |
+
Method | +Description | +Call example | +
---|---|---|
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 }); |
+
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 }); |
+
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 }); |
+
Method | +Description | +Call example | +
---|---|---|
areSettingsValid |
+Return true in the settings are valid |
+AutoNumeric.areSettingsValid({ options }) |
+
isManagedByAutoNumeric |
+Return true if the given DOM element (or selector string) has an AutoNumeric object that manages it. |
+AutoNumeric.isManagedByAutoNumeric(domElement); AutoNumeric.isManagedByAutoNumeric('#theInput'); |
+
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: '#' }]); |
+
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'); |
+
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(); |
+
You can check the AutoNumeric official website which contains additional tools and examples.
+For questions and support please use the Gitter chat room or IRC on Libera Chat #autoNumeric.
+The issue list of the Github repository is exclusively for bug reports and feature requests.
+Feel free to donate via Patreon to support autoNumeric development.
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). +
+Info
+Each option can be accessed as a function to update its value, ie. anElement.options.<optionName>()
, where <optionName>
can be any option name from the options list.
Hint
+As soon as the options are modified, the AutoNumeric-managed input content is re-formatted accordingly.
+If you've initialized your input with AutoNumeric.multiple()
, you can use the returned Array1 to update all the AutoNumeric objects at once:
+
// AutoNumeric initialisation for multiple elements
+const anElements = new AutoNumeric.multiple('.numeric', 42, ['French']);
+
+// Update the options globally for all the inputs with one function call:
+// Modify only a specific element in the array
+anElements[2].update({ decimalPlaces: 3 });
+// or modify all the elements at once
+anElements.forEach(a => a.update({ currencySymbol: '#' })); // or .set(), etc.
+
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.
+
Lastly, the option object can be accessed directly, thus allowing to query each options globally too.
This allows to inspect the current options used.
+
anElement.getSettings(); // Return the options object containing all the current AutoNumeric settings in effect
+
The AutoNumeric.multiple()
function will always return an Array
, even if there is only one element selected. ↩
The old and outdated documentation for the deprecated v1.9
and v2
versions can be found in the v1.9 documentation and v2 documentation files.
For some examples and an option code generator for the old v1.9.*
version, take a look here.
Disclaimer 1: v1.9
has been superseeded by v4.*
and is not longer supported. Please consider switching to the latest version.
Disclaimer 2: This documentation may be outdated.
Please consider using the Readme that always has up-to-date information.
The complete list of options are below
+There are multiple ways for changing the options. To format "123456789.00" to "€ 123.456.789,00" you could do the following:
+options - pass when initializing autoNumeric +
$(document).ready(function(){
+ $(selector).autoNumeric("init", {
+ digitGroupSeparator: '.',
+ decimalCharacter: ',',
+ currencySymbol: '€ '
+ });
+});
+
HTML5 data - *By convention the data attribute is written in lower-case. Compound words (example: "decimalCharacter") need to be split and separated by a dash. The equal sign separates the name and value. The value should be enclosed with quote marks. If multiple options are being used they each need to have the own data attribute.
+<input type='text' name="someName" value="1234.56" data-a-sep="." data-a-dec="," data-a-sign="€ "/>
+
$.extend method - in this example ASP.NET current culture settings are passed.
+note: - this can change defaults globally
+<script type="text/javascript">
+
+ $(document).ready(function() {
+ $.extend($.fn.autoNumeric.defaults, {
+ digitGroupSeparator: '@System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator',
+ decimalCharacter: '@System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator',
+ currencySymbol: '@System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol'
+ });
+
+ $('selector').autoNumeric('init');
+
+ });
+
+</script>
+
<script type="text/javascript">
+
+ /* the callback function must be defined prior to initiating autoNumeric */
+
+ var functionName = function() {
+ /* your code here */
+ var value = 4; /* example only */
+ return value;
+ }
+
+ /* initiates autoNumeric and passes a function */
+
+ $('selector').autoNumeric('init', { decimalPlaces: functionName })
+
By default autoNumeric formats the default values on page ready. The values should be sent as text. autoNumeric supports the use on locale formats with the following rules:
+value / text | +valid? | +
---|---|
"123456" | +true | +
"123456.78" | +true | +
"123456,78" | +true | +
"-123456" | +true | +
"-123456.78" | +true | +
"-123456,78" | +true | +
"123456-" | +true | +
"123456.78-" | +true | +
"123456,78-" | +true | +
"123,456.78" | +false | +
"123.456.78" | +false | +
"-123456.78-" | +false | +
"€ 123456.78" | +false | +
"2.034E23" | +false | +
Default values and values being "set" need to fall with the min/max range.
+If you do not want the default values formatted on set the option from "formatOnPageLoad: true" to "formatOnPageLoad: false"
+During page load / re-load autoNumeric compares the value of the input "$this[0].value" and the "$this.prop('defaultValue')" value. If they are equal and "formatOnPageLoad: true" the value is formatted.
+What happens during ASP.NET form post-back is the input tag is re-rendered. An example Page loaded
+<input type='text' name="someName" id="someID" class='someClass' value="" />
+
+// user enters "1234.56" => "1,234.56" with default settings
+// during post-back the input is re-rendered and is now showing the new default value.
+
+<input type='text' name="someName" id="someID" class='someClass' value="1,234.56" />
+
Once the page is reloaded on post-back and autoNumeric compares $this[0].value" and the "$this.prop('defaultValue')" and sees they are equal it attenpts to format the values. From the above valid value table the "1,234.56" would be invalid.
+There are two options that can handle the postback event "formatOnPageLoad" & "defaultValueOverride":
+1) "formatOnPageLoad option" - this option controls if default values are formatted on page load. By default it is set to "formatOnPageLoad: true"
+Change the "formatOnPageLoad" option to "formatOnPageLoad: false" - this can be done when initalizing "init" the element as an option or as HTML5 data attribute
+If there are no default value(vs) simply initialize 'init' the element
+ +If there is a default value you will need to pre-format the default value as shown +<!-- it is important that a preformatted default values match the options/settings.
+ mismatches could cause errors -->
+<input type='text' name="someName" value="1,234.56"/>
+
2) "defaultValueOverride" option was created to help ASP.NET postabck and is used if "formatOnPageLoad: true" is set 'true'.
+Note: "defaultValueOverride" option should be the same value as the default value
+ +// 'defaultValueOverride' is the value of the default value above
+$('selector').autoNumeric('init', {defaultValueOverride: "1234.56"});
+
The minimum and maximum values and decimal places are set via minimumValue: '-9999999999999.99' and maximumValue: '9999999999999.99' option. The decimal places are determined be the number of characters following the "." decimal point.
+minimumValue: | +maximumValue: | +decimal places | +
---|---|---|
"0" | +"9999999999" | +0 | +
"0.00" | +"99999999.99" | +2 | +
"0.00" | +"9999999999" | +2 | +
"-9999999" | +"9999999.999" | +3 | +
Notes: +- minimumValue should always be a lower value than maximumValue! +- minimumValue and maximumValue can be both positive or negative but do so with caution. +- If the range of the minimumValue & maximumValue is small or you make them numbers other then "9" nines (example "1000) you could create a situation where the uses will need to delete characters before the can obtain the minimumValue / maximumValue limits.
+Additional documentation for v1.9
can be found on the old website.
Disclaimer 1: v1.9
has been superseeded by v4.*
and is not longer supported. Please consider switching to the latest version.
Disclaimer 2: This documentation may be outdated.
Please consider using the Readme that always has up-to-date information.
The following is an uncomplete list of the methods and settings/options that control autoNumeric 2.0.*
:
'init'
$('someSelector').autoNumeric();
$('someSelector').autoNumeric('init');
$('someSelector').autoNumeric({options});
$('someSelector').autoNumeric('init', {options});
'destroy'
$('someSelector').autoNumeric('destroy');
'wipe'
$(someSelector).autoNumeric('wipe');
'update'
$('someSelector').autoNumeric('update', {options});
'set'
$('someSelector').autoNumeric('set', value);
// see 'unSet'
$(someSelector).autoNumeric('unSet');
// returns "nnnn.nn" or "-nnnn.nn"$(someSelector).autoNumeric('unSet', '.-');
// returns "nnnn.nn" or "nnnn.nn-" // trailing negative sign$(someSelector).autoNumeric('unSet', ',');
// returns "nnnn,nn" or "-nnnn,nn" // comma as decimal seperator$(someSelector).autoNumeric('unSet', ',-');
// returns "nnnn,nn" or "nnnn,nn-" // comma as decimal separator & trailing negative sign'reSet'
$(someSelector).autoNumeric('reSet');
'get'
$(someSelector).autoNumeric('get');
// returns "nnnn.nn" or "-nnnn.nn"$(someSelector).autoNumeric('get', '.-');
// returns "nnnn.nn" or "nnnn.nn-" // trailing negative sign$(someSelector).autoNumeric('get', ',');
// returns "nnnn,nn" or "-nnnn,nn" // comma as decimal seperator$(someSelector).autoNumeric('get', ',-');
// returns "nnnn,nn" or "nnnn,nn-" // comma as decimal separator & trailing negative sign'getString'
$(someSelector).autoNumeric('getString');
// returns "nnnn.nn" or "-nnnn.nn"$(someSelector).autoNumeric('getString', '.-');
// returns "nnnn.nn" or "nnnn.nn-" // trailing negative sign$(someSelector).autoNumeric('getString', ',');
// returns "nnnn,nn" or "-nnnn,nn" // comma as decimal seperator$(someSelector).autoNumeric('getString', ',-');
// returns "nnnn,nn" or "nnnn,nn-" // comma as decimal separator & trailing negative sign'getArray'
$(someSelector).autoNumeric('getArray');
// returns "nnnn.nn" or "-nnnn.nn"$(someSelector).autoNumeric('getArray', '.-');
// returns "nnnn.nn" or "nnnn.nn-" // trailing negative sign$(someSelector).autoNumeric('getArray', ',');
// returns "nnnn,nn" or "-nnnn,nn" // comma as decimal seperator$(someSelector).autoNumeric('getArray', ',-');
// returns "nnnn,nn" or "nnnn,nn-" // comma as decimal separator & trailing negative sign'getSettings'
$('someSelector').autoNumeric('getSettings');
// returns the jQuery data opbect with settings $('someSelector').autoNumeric('getSettings').decimalCharacter;
// returns the 'decimalCharacter' valuedecimalCharacter
with the desired settings / option nameFor more examples, documentation and the option code generator please take a look at http://www.decorplanit.com/plugin/.
+Additionally, autoNumeric now supports formatting and unformatting directly without having to first initiate a DOM element :
+'autoUnformat'
For instance, to unformat, you would use : +
let autoNumericOptions = { digitGroupSeparator: '.', decimalCharacter: ',', decimalCharacterAlternative: '.', currencySymbol: ' €', currencySymbolPlacement: 's', roundingMethod: 'U' };
+let formattedString = "1.234,56 €";
+$.fn.autoUnformat(formattedString, autoNumericOptions); // Returns 1234.56
+
'autoFormat'
For instance, to format, you would use : +
let autoNumericOptions = { digitGroupSeparator: '.', decimalCharacter: ',', decimalCharacterAlternative: '.', currencySymbol: ' €', currencySymbolPlacement: 's', roundingMethod: 'U' };
+let number = 1234.56;
+$.fn.autoFormat(number, autoNumericOptions); // Returns "1.234,56 €"
+
visit autoNumeric's home page for an easy to use settings and option code generator
+Disclaimer : This may be outdated. Please refer to the Readme or directly in the detailed comments in the source code for the defaultSettings
object.
controls the thousand separator character +- digitGroupSeparator: ',' // Comma +- digitGroupSeparator: '.' // Dot +- digitGroupSeparator: ' ' // Normal space +- digitGroupSeparator: '\u2009' // Thin-space +- digitGroupSeparator: '\u202f' // Narrow no-break space +- digitGroupSeparator: '\u00a0' // No-break space +- digitGroupSeparator: '' // No separator +- digitGroupSeparator: "'" // Apostrophe +- digitGroupSeparator: '٬' // Arabic thousands separator +- digitGroupSeparator: '˙' // Dot above
+When true only numbers and the decimal character is visible while the input has focus +- showOnlyNumbersOnFocus: false (default) +- showOnlyNumbersOnFocus: true removes currency sign and thousand seperator while the input has focus. Help on some mobile devices
+controls the digital grouping and the placement of the thousand separator +- digitalGroupSpacing: '3' produces 333,333,333 (default) +- digitalGroupSpacing: '2' produces 22,22,22,333 India's Lakhs +- digitalGroupSpacing: '2s' produces 22,333,22,22,333 scaled version of India Lakhs +- digitalGroupSpacing: '4' produces 4,4444,4444 used in some Asian country's
+controls the decimal character +- decimalCharacter: ',' // Comma +- decimalCharacter: '.' // Dot +- decimalCharacter: '·' // Middle-dot +- decimalCharacter: '٫' // Arabic decimal separator +- decimalCharacter: '⎖' // Decimal separator key symbol
+this was developed to accommodate for different keyboard layouts. decimalCharacterAlternative allows you to declare an alternative key to enter the decimal separator assigned in decimalCharacter +- decimalCharacterAlternative: null (default)
+displays the desired currency symbol (examples: € or EUR). Note: other symbols can be used, such as %, °C, °F, km/h & MPH the possibilities are endless +- currencySymbol: '' none (default) +- examples: currencySymbol: 'U$D' or currencySymbol: 'EUR'
+controls the placement of the currency symbol (prefix or suffix) +- currencySymbolPlacement: 'p' prefix to the left (default) +- currencySymbolPlacement: 's' suffix to the right
+placement of the negative sign. This position is relative to the currencySymbol position + - negativePositiveSignPlacement: 'l' (default) left of currency sign + - negativePositiveSignPlacement: 'r' right of currency sign + - negativePositiveSignPlacement: 's' suffix places the sign to the right of the numbers + - negativePositiveSignPlacement: 'p' prefix places the sign(-) to the felt of the numbers + - Examples:
+format | +options to achieve format | +
---|---|
-1,234.56 | +defaults | +
1,234.56- | +{negativePositiveSignPlacement: 's'} | +
-$1,234.56 | +{currencySymbol: '$'} | +
$-1,234.56 | +{currencySymbol: '$', negativePositiveSignPlacement: 'r'} | +
$1,234.56- | +{currencySymbol: '$', negativePositiveSignPlacement: 's'} | +
1,234.56-$ | +{currencySymbol: '$', currencySymbolPlacement: 's'} | +
1,234.56$- | +{currencySymbol: '$', currencySymbolPlacement: 's', negativePositiveSignPlacement: 'r'} | +
-1,234.56$ | +{currencySymbol: '$', currencySymbolPlacement: 's', negativePositiveSignPlacement: 'p'} | +
Allows additional text as a suffix +- suffixText: '' (default) no suffix defined +- suffixText: 'test' example: 123,4.56 test +- Numbers and minus sign (-) are not allowed and will cause an error
+controls the minimum value allowed +- minimumValue: '-9999999999999.99' (default) +- Must be set as text +- Can be negative or positive but must be less than 'maximumValue'
+controls the maximum value allowed +- maximumValue: '9999999999999.99' (default) +- Must be set as text +- Can be positive or negative but must be greater than 'minimumValue'
+Note: setting the minimumValue and maximumValue to both positive or negative with situations that limits the users ability to enter the proper values
+Note: This has been deprecated in v4
+overrides the decimal places that that are set via the minimumValue/maximumValue values
+- decimalPlacesOverride: null (default method)
+- decimalPlacesOverride: '4' overides the default and allows 4 decimal places
sets the rounding method used (12 different available - case sensitive)
+option | +Rounding method | +
---|---|
'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' | +Rounding "to the nearest .00 or .05" | +
'U05' | +Rounds up to next .00 or .05 | +
'D05' | +Rounds down to next .00 or .05 | +
controls padding of the decimal places +- allowDecimalPadding: true always pads the decimal with zeros (default) +- allowDecimalPadding: false no padding
+controls if negative values are display with brackets when the input does not have focus +- negativeBracketsTypeOnBlur: null no brackets use for negative values (default) +- negativeBracketsTypeOnBlur: '(,)' +- negativeBracketsTypeOnBlur: '[,]' +- negativeBracketsTypeOnBlur: '{,}' +- negativeBracketsTypeOnBlur: '<,>'
+controls input currency sign display behavior when the input does not have a value '' +- emptyInputBehavior: 'focus' (default) the currency symbol will be displayed on focus +- emptyInputBehavior: 'press' currency symbol will not be displayed until the first key is pressed +- emptyInputBehavior: 'always' currency symbol is always displayed with or without a value
+controls leading zeros behavior +- leadingZero: 'allow' allows leading zero to be entered. They are removed on focusout event (default) +- leadingZero: 'deny' leading zeros not allowed. +- leadingZero: 'keep' leading zeros allowed and will be retained on the focusout event
+controls the 'alt' & 'a' select key combination +- selectNumberOnly: false (default) selects all characters within the input +- selectNumberOnly: true selects only the numbers +- note: if the currency symbol is between the numeric value and the negative sign only the numeric characters will be selected
+controls if default values are formatted on page ready (load) +- formatOnPageLoad: true default values are formatted on page ready (default) +- formatOnPageLoad: false default values are NOT formatted on page ready
+helper option for ASP.NET post-back +- should be the value of the un-formatted default value +- this can be set as an option when initializing autoNumeric or as HTML5 data +- examples: +- no default value='' {defaultValueOverride: ''} +- value=1234.56 {defaultValueOverride: '1234.56'}
+removes the format on the submit event +- unformatOnSubmit: false (default) does not remove the formatting +- unformatOnSubmit: true - removes the formatting on the submit event +- this can be done globally via the extend method or by elemnt via the jQuery selector +- output is always "nnnn.nn" or negative "-nnnn.nn". n = 0-9
+error handling function +- showWarnings: true - (default) throws errors - helpful during developing. +- showWarnings: false - stops most errors from being thrown.
+ + + + + + + + + + + + + +