NumBox API v1.1.0

Full API - Methods & Properties

NumBox API Cheat Sheet
Method   (Click for Details) Chainable Usage Summary
.NumBox()
.NumBox({ property: value, … })
.NumBox('setup')
.NumBox('setup', { property: value, … })
Different ways of specifying the initial set up of NumBox
against type="text" or type="number" inputs, with or without
an optional list of configuration properties. Required first.
Call once per input unless you use 'destroy' between calls.
.NumBox('destroy') Disassociates NumBox (including events) from inputs.
.NumBox('getFormatted') Returns display formatted number as a string. e.g. $1,234.50.
.NumBox('getRaw') Returns raw number for calculations, et cetera. e.g. 1234.5.
.NumBox('setRaw', rawValue) Lets you change NumBox value programmatically.
Optional as NumBox picks up existing value during set up.
.NumBox('autoScroll', 'auto' | true | false) Whether or not to help scroll input box higher up the screen.
Handy on mobile devices where pop-up keyboards can appear.
Also available as a property in 'setup'. Defaults to 'auto'.
.NumBox('onFocus', 'fnCallbackName') Optional. Use if you need to hook gained focus events.
Also available in 'setup'. Fn name is a quoted string.
Callback fires on the input’s focus events.
.NumBox('onBlur', 'fnCallbackName') Optional. Use if you need to hook lost focus events.
Also available in 'setup'. Fn name is a quoted string.
Callback fires on the input’s blur events.
.NumBox('onKeydown', 'fnCallbackName') Optional. Use if you need to hook key press events.
Also available in 'setup'. Fn name is a quoted string.
Callback fires on the input’s keydown events.
.NumBox('onInput', 'fnCallbackName') Optional. Use if you need to hook value is changing events.
Also available in 'setup'. Fn name is a quoted string.
Callback fires on the input & propertychange events.
.NumBox('onPaste', 'fnCallbackName') Optional. Use if you need to hook paste events.
Also available in 'setup'. Fn name is a quoted string.
Callback fires on the input’s paste events (if supported.)
Additional Considerations…

Some Quick Examples:

        $('#money'  ).NumBox(); // defaults to dollars
        $('#money'  ).NumBox({symbol: '€', location: 'r'});
        $('#plastic').NumBox({type: 'ccard'});
        $('#percent').NumBox({type: 'percent'});
        
        $('.NumBox' ).NumBox('destroy'); // '.NumBox' = all
        
        var forShow = $('#input').NumBox('getFormatted');
        var forCalc = $('#input').NumBox('getRaw');
        $('#input'  ).NumBox('setRaw',  1234.5 );
        $('#input'  ).NumBox('setRaw', '1234.5');
        
        $('.NumBox' ).NumBox('autoScroll', true);
        
        $('.NumBox' ).NumBox('onFocus', 'callback');
        $('.NumBox' ).NumBox('onInput', 'callback');
        
        function callback(event, valid)
        {
            // all callbacks pass the jQuery event object
            console.log
            (
                event.currentTarget.id + ' : ' +
                event.type
            );
            
            // input also has a change permitted Boolean
            if (typeof valid === 'boolean')
            {
                console.log
                (
                    '>> valid = ' + valid.toString()
                );
            }
        }
    



Setup Method

Syntax: $(elements).NumBox();
$(elements).NumBox({ Property: Value, … });
$(elements).NumBox('setup');
$(elements).NumBox('setup', { Property: Value, … });
Example: $('#field').NumBox({ symbol: '£', max: 100000.00 });
Summary: Must be first NumBox method applied to an input. Call only once for elements, unless you use the Destroy method between calls.
If a property list is not provided, or if the defaults are not overriden, NumBox defaults to providing a dollar currency.

Optional Property Default Value Usage & Permissible Values
type 'currency' Handy presets that conveniently save you from having to set multiple properties. Makes your code more readable from a maintenance perspective. Since 'currency' is the default, calling .NumBox() without any parameters is the same as specifying a dollar currency format. If using a credit card type, please note that credit card checksums (Luhn algorithms) are not applied. NumBox allows incomplete numbers to be entered as this is a better user experience than wiping out incomplete entries.
'ccard' Option best suited for a wide range of credit cards and store cards. Allows up to sixteen digits to be entered. Formats number in a VISA/MasterCard credit card style with a hyphen every four digits.
'ccard-15' Specifically targets American Express credit cards. Allows up to fifteen digits to be entered, starting with a 34 or 37. Formats number in an American Express credit card style.
'ccard-16' Specifically targets VISA and MasterCard credit cards. Allows up to sixteen digits to be entered, starting with a 4 or 51 through 55. Formats number in a VISA/MasterCard credit card style with a hyphen every four digits.
'currency' Shortcut for specifying a decimal number to two decimal places preceded by a dollar sign. Default range is $0.00 to $999,999.99 but can be changed. Defaults can be overridden by specifying additional properties such as the currency symbol, symbol location (to left or right of number) and number of decimal places.
'decimal' Shortcut for specifying a decimal number defaulting to two decimal places without a currency or other symbol. Default range is 0.00 to 999,999.99. Defaults can be overridden by specifying additional properties.
'ein' Specifically targets U.S. Employer Identification Numbers that are issued by the U.S. Internal Revenue Service. Allows up to nine digits to be entered. Formats the number with a hyphen after the second digit.
'integer' Shortcut for specifying an integer number without a currency or other symbol. Default range is 0 to 999,999 but this can be overridden with a new max value.
'percent' Shortcut for specifying an integer number followed by a percent sign with a range of 0 through 100. Defaults can be overridden if you want decimal places or higher maximum value. Example:
$('#increase').NumBox({ type: 'percent', max: 200 });
'ssn' Specifically targets U.S. social security numbers. Allows up to nine digits to be entered. Formats the number with a hyphen after the third and fifth digits.
'zip' or 'zip5' Specifically targets 5 digit U.S. ZIP codes. Allows up to five digits to be entered without any formatting.
'zip9' Specifically targets nine digit U.S. ZIP codes, and allows five digit ZIP codes. Up to nine digits can be entered. Formats the number with a hyphen after the fifth digit.
places 2 (integer) Specifies how many decimal places. Set to zero if you only want to work with integers.
Not applicable for card types, EINs or SSNs.
min 0 (decimal) Minimum value permitted. Currently can only be zero.
NumBox will be improved to permit negative numbers in future.
Not applicable for card types, EINs or SSNs.
max 999999.99 (decimal) Maximum value permitted. Can be adjusted as desired.
Must be the same or higher than the minimum value permitted.
Not applicable for card types, EINs or SSNs.
step 'min' This is the HTML5 step attribute, which is the amount that the number increments or decrements when you press the up or down spinner buttons, which some browsers provide for type=number inputs. According to the W3C specifications, the step setting should also limit the number itself, but how this is implemented in browsers varies and should not be relied upon. If you plan to hide the spinner buttons, (recommended as a better user experience,) then you can just leave this set to 'min'. Please never set this to 'any' (an HTML5 option) since that stops some mobile devices from displaying a numeric keyboard.
'min' NumBox will automatically set the step attribute to the lowest possible value based upon the number of decimal places. e.g. For two decimal places, NumBox will automatically set a step value of '0.01'. If you choose to display spinners and the number will have frequent micro-adjustments, this can be a convenient setting.
'decimal #' You can specify your own step value as a decimal number, but it needs to be contained within quotes. For example a step value of '1' on a NumBox set up as a dollar currency to two decimal places will, theoretically, only allow a number to be incremented or decremented in whole dollars, but when displayed, you will see the .00 cents too as part of the formatting. Note the word "theoretically". Not all browsers behave the same way. So, if you intend to override NumBox, you should test what is appropriate in all of your target environments.

On iPhones and iPads in particular, overriding 'min' with an integer typically cause a numeric keyboard to appear without a decimal point or an option to change keyboards. Similarly overriding 'min' with a number smaller than an integer typically gives you the decimal point in your numeric keyboard.
symbol '$' Specifies a symbol to display alongside the number, either immediately to the left or right of the number. Can be set to empty quotes, '', if not desired. Can also contain multiple characters such as 'USD' or even words, as shown in the atomic radius example. Not applicable for card types, EINs or SSNs.
location 'l' Location of symbol in relation to the number being displayed.
Not applicable for card types, EINs or SSNs.
'l' Symbol is placed immediately to the left of the number.
'r' Symbol is placed immediately to the right of the number.
separator ',' or '-' To make a long number more readable, you may want to segment it into groups of a fixed number of digits with a character separating each segment. This property specifies the character to be used to separate each segment, and, for real numbers, defaults to a comma. For credit cards, EINs and SSNs, the character defaults to a hyphen. You can specify your own character choice, but it cannot be a decimal point or number. Applicable for all types, including credit cards, EINs, SSNs and real numbers. Use empty quotes, '', if you don’t want to see a separating character.
grouping 3 or 4 (integer) To make a long number more readable, you may want to segment it into groups of a fixed number of digits with a character separating each segment. This property specifies how many digits are to be grouped together into a segment. In the case of real numbers, segmenting occurs every x digits to the left of the decimal point. In all other cases (credit cards, EIN and SSN) segmenting occurs every x digits moving from left to right. Only applicable for ccard, ccard-16 and real number types. Not applicable for ccard-15, EIN or SSN types, which have irregular grouping intervals that NumBox handles directly. Must be an integer that is larger than zero.
autoScroll 'auto' When you tap on an HTML input box using a phone, typically your browser viewport is resized to the top half of your phone's screen, and the lower half is replaced with a virtual keyboard, so you can type an entry into the input box. However, sometimes the box you just tapped on is hidden by the virtual keyboard that just popped up. NumBox can optionally try to scroll the browser viewport so that the input box is scrolled up automatically to remains in view after the keyboard has appeared.
'auto'
For mixed mobile/desktop use with responsive designs.
The 'auto' string setting, tells NumBox to set the value to true if it thinks the browser is on a mobile device, and to set the value to false if it thinks the browser is on a desktop device. This way, mobile devices can take advantage of the auto-scroll feature, while desktop browser experiences remain unchanged.
true
Recommended for mobile-only use – PhoneGap, etc.
NumBox will attempt to scroll the browser viewport so that the input box is more likely to be in a mobile browser’s viewport once the pop-up keyboard has appeared. In case you have a fixed header and footer that stays put and doesn't scroll, such as can be achieved using jQuery Mobile’s data-position="fixed" attribute, NumBox needs to know the area that can be scrolled. You should mark the scrollable area in one of two ways:
  1. A div  with a data-role="content" attribute.
  2. An element with an id="content" attribute.
If you don’t have a fixed position header, you could apply one of these attributes to the <body> element. NumBox won’t try to scroll the browser viewport unless one of these attributes are found.
false
For desktop-only use or sites not catering for mobiles.
NumBox will never attempt to scroll the browser viewport.
This can be advisable if a mobile user has to keep on zooming or panning.
onFocus '' (empty string) You should set this property if you want to hook the focus event of the input. The value should be set to a string which is the name of the function you want to be called during the event. Please see the Hooking Event Handlers section for full details.
onBlur '' (empty string) You should set this property if you want to hook the blur event of the input. The value should be set to a string which is the name of the function you want to be called during the event. Please see the Hooking Event Handlers section for full details.
onKeydown '' (empty string) You should set this property if you want to hook the focus event of the input. The value should be set to a string which is the name of the function you want to be called during the event. Please see the Hooking Event Handlers section for full details.
onInput '' (empty string) You should set this property if you want to hook the input or propertychange events of the input. The value should be set to a string which is the name of the function you want to be called during the event. Please see Hooking Event Handlers .
onPaste '' (empty string) You should set this property if you want to hook the focus event of the input. The value should be set to a string which is the name of the function you want to be called during the event. Please see the Hooking Event Handlers section for full details.



Destroy Method

Syntax: $(elements).NumBox('destroy');
Example: $('#field').NumBox('destroy');
Summary: Disassociates NumBox from the provided elements. You can use ".NumBox" as your jQuery selector to choose all NumBox inputs.
You may find this useful if you want to prevent NumBox events from firing on inputs that were previously associated with NumBox.


Obtaining Values

Syntax: $(oneElement).NumBox('getFormatted');
$(oneElement).NumBox('getRaw');
Example: $('#myField').NumBox('getFormatted');

When the NumBox element has the focus, it’s value attribute will be either an empty string or a raw unformatted number. When the NumBox element doesn’t have the focus, such as when a form is submitted, it’s value attribute will be the display formatted number, including currency symbol (if applicable) and grouping separators. You can explicitly obtain either the raw number or formatted number using these two helper methods:

getFormatted Returns a fully formatted number such as "$1,234.50" as a string.
getRaw Returns a raw number such as "1234.5" as a string, without any symbols or grouping characters.
Social security numbers and employer identification numbers can have leading zeros.

If you intend to save the raw number to a database when a form is submitted, you could try something like this:

        <form method="post" action="SomePageThatSavesToDb.html">
            <div>
                <label for="inputUSD">US Dollars:</label>
                <input  id="inputUSD" type="number" value="0" placeholder="Please enter an amount" />
                <input  id="otherWay" type="hidden" value="0" />
            </div>
            <div>
                <button id="btnSave"  type="submit" title="Save the raw value">Save</button>
            </div>
        </form>
        
        <script type="text/javascript">
            $(document).ready(function()
            {
                $('#inputUSD').NumBox();
                $('#btnSave').click(function(event)
                {
                    $('#inputUSD').value = $('#inputUSD').NumBox.raw(); // or
                    $('#otherWay').value = $('#inputUSD').NumBox.raw();
                });
            });    
        </script>
    


Setting Values

Syntax: $(elements).NumBox('setRaw', rawValue);
Example: $('#field').NumBox('setRaw', 1234.5);
$('#field').NumBox('setRaw', '023456789'); // SSN

As long as the input field has it’s value set before you first apply NumBox’s setup method, then you don't necessarily need to use the setRaw method. When .NumBox() is first applied, any existing number found in the field will be formatted according to your configuration options, providing that the number fits the rules you've created. For example, if you specify .NumBox({'integer'}) then you should not have pre-populated the field with an initial value of "0.01".

If you want to set the value after NumBox has been set up for your input, then you should use this method. The number you provide should be a raw number, devoid of any symbol or spacing characters, and it can be provided as either a string, an integer or a decimal. If your value can start with a leading zero, such as a social security number or employee identification number, then you should always pass the “number” in as a string, so you don”t potentially lose any leading zero. You should also ensure that the provided number conforms to the configuration options that you've chosen.

It may be useful to remember that setRaw can be applied to many fields at once if they will all have the same value.


Autoscroll Helper

Syntax: $(elements).NumBox('autoScroll', 'auto' | true | false);
Example: $('#field').NumBox('autoScroll', true);

A detailed description of what autoScroll is for, and it’s settings, can be found in the Setup Method.
Broadly, NumBox's auto-scroll feature helps the input box stay above any virtual keyboards that can
pop-up on-screen on a mobile device. As a general rule of thumb: There are two ways you can set up auto-scrolling for your NumBox inputs:
  1. By providing the appropriate property in NumBox’s Setup Method. For example:
    $('#creditcard').NumBox({type: 'ccard', autoScroll: true});
     
  2. By using the autoScroll method after set up has been completed. For example:
    $('#creditcard').NumBox('autoScroll', true);

You’ll probably want to use a consistent autoScroll setting for all NumBox inputs.
Since NumBox adds an HTML class called “NumBox” to all of it’s inputs, you can do this:
$('.NumBox').NumBox('autoScroll', false);

In order for autoScroll to work, you first need to define the content area that can be scrolled.
This can be done with a simple HTML content tag on your page in one of two ways:
  1. A div with a data-role="content" attribute.
  2. An element with an id="content" attribute.

If your page doesn't have a fixed header that stays when you scroll, you could try doing this:
<body id="content"> or <body data-role="content">

If you don’t set up a content tag, no error will occur and NumBox will gracefully ignore autoScroll.


Hooking Event Handlers

Syntax: $(elements).NumBox('onFocus', 'yourCallbackFunctionName');
$(elements).NumBox('onBlur', 'yourCallbackFunctionName');
$(elements).NumBox('onKeydown', 'yourCallbackFunctionName');
$(elements).NumBox('onInput', 'yourCallbackFunctionName');
$(elements).NumBox('onPaste', 'yourCallbackFunctionName');
Example: $('.input').NumBox('onInput',  'highlightErrors');

You shouldn’t directly plug in to any of the following events on NumBox inputs, since NumBox needs to use them:

If you'd like to hook any of the above on NumBox inputs, please use the NumBox callback mechanism instead.
NumBox can then hand-off control to your custom JavaScript function once it has finished dealing with an event.
Remember though that if you use NumBox’s Destroy Method on an input, then NumBox will no longer hand-off.

There are two ways you can tell NumBox the name of your function that you'd like NumBox to call:
  1. By providing the appropriate property in NumBox’s Setup Method. For example:
    $('#creditcard').NumBox({type: 'ccard', onKeydown: 'fnMakeAClickingNoise'});
     
  2. By using one of the five NumBox callback methods outlined in the table below. For example:
    $('#creditcard').NumBox('onKeydown', 'fnMakeAClickingNoise');

If you've previously set up a NumBox callback and want to take it down later, you can pass an empty string:
$('#creditcard').NumBox('onKeydown', '');

If you have multiple NumBox inputs on a page that will all use the same callback,
its probably easiest (and DRYer) to go with the second method, so you can
hook them all at once using '.NumBox' as your jQuery selector:
$('.NumBox').NumBox('onKeydown', 'fnMakeAClickingNoise');

Whichever method you use, the function name you provide must be in quotes. (Provided as a string.)
You should only provide the name, without any parentheses, and correctly capitalized!

Callback Method Parameters Forwarded Important Notes on Use
onFocus jQuery event object Callback occurs when the input gains focus, during the focus event.
onBlur jQuery event object Callback occurs when the input loses focus, during the blur event.
onKeydown jQuery event object Callback usually occurs when a key is pressed, during the keydown event. You can use this event to obtain a key code, to identify which key was pressed. Some browsers do not send every key press, so use with caution. Google Chrome for Android, (not the native browser,) also has a major flaw, and sends a zero for all key presses, making it impossible to identify the key.
onInput jQuery event object,
input succeeded Boolean
Callback usually occurs when the value of the input is changed by the user typing, while the input still has the focus. This is during the input event on all modern browsers. On older Microsoft browsers (IE8-) which don’t support the standard input event, NumBox hooks Microsoft’s proprietary propertychange event instead. However, since propertychange, unlike input, also fires when a value is changed via JavaScript, NumBox takes care not to hand off to your callback unless a keydown event is also fired. To add fuel to the fire, IE8 has a bug where it doesn't fire propertychange on the first key press.
onPaste jQuery event object Callback sometimes occurs during a paste event, when the user is copy-pasting. This event should not be relied upon as it is not standard and only some browsers support it. Additionally, as NumBox blocks certain key presses during the keydown event, such as ctrl-v (Windows paste shortcut) then we may never get to this event.

These are parameters/arguments that NumBox passes on to your function.
  An example callback function that consumes these parameters is shown at the top of the page.


Additional Considerations

Consistent Styling

NumBox deliberately does not create any new UI components or attempt to style inputs, which makes it suitable for virtually all layout systems, including Twitter Bootstrap, Zurb Foundation, and jQuery Mobile. It does however, toggle input boxes’ types between type="number" and type="text", depending on the browser and if the mode is input or display. It is therefore suggested that you use the same styling for both input types. For example:

        input[type="number"],
        input[type="text"]
        {
            width: 100%;    // or
            width: 200px;   // etc.
        }
    

.NumBox Class

You also have the option of styling all NumBox inputs in CSS using the .NumBox class, which NumBox adds to all of it’s inputs.
The class can also conveniently be used with JavaScript and in jQuery selectors. For example:

        $('.NumBox').NumBox('setRaw', 0).NumBox('destroy').prop('disabled', true);
    

Disabling Spinners

For the most consistent look, it is typically recommended that the up/down spinners/arrows that appear in some browsers for input type="number" are disabled. On several browsers, even if you've correctly coded your CSS styles for a consistent width, and tinkered with box-sizing etc, numeric inputs that have a focus will be shorter in length than other inputs. This is due to an extra right margin on the spinners. The spinners are also not usually styled by layout libraries, so they can often look pretty awful with miniscule grey button arrows. Finally, spinners are totally impractical unless you're spinning a short range. e.g. 0% to 100%. Try spinning up to $1,000.00! Oh, and do you want to input a credit card number or social security number using spinners? Spinners are great with specialized time pop-ups (0-24, 0-60) but you don't need them for most numeric inputs, which is probably why most browsers made the wise decision not to implement them. Even on a small phone, it is easier and more importantly faster to use the numeric keyboard that NumBox pops-up to enter a number than using a spinner. So, spinners need to die go away! If you don’t agree, please feel free to (politely) debate the subject on the NumBox Community Forums!

If you want to disable the spinners then you can use the contents of the CSS file that was downloaded along with NumBox:

        /* Webkit: Android, Chrome, iOS, Safari */
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button
        {
            -webkit-appearance: none;   /* display: none alt can crash on hover */
            margin: 0px;                /* sometimes margin is left for spinner */
        }
    

Since these are just a few lines of CSS, you might prefer to incorporate them directly into your own CSS file.