NumBox API v1.1.0
Full API - Methods & Properties
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();
|
---|---|
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.
|
||||||||||||||||||||||
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.
|
||||||||||||||||||||||
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.
|
||||||||||||||||||||||
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.
|
||||||||||||||||||||||
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');
|
---|---|
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);
|
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:
-
Use 'auto' (including quotes)
if your web site visitors are using a mix of mobile and desktop
browsers, and your site has a responsive design that is very well suited to mobile devices.
(No zooming or panning required.) NumBox will then only use autoScroll if it thinks the device
is a mobile device. This is the default setting. Stay with it if you’re unsure which is the best option.
-
Use true
if you’re guaranteed to be in a mobile-only environment, or writing a mobile app,
such as with Apache Cordova, PhoneGap, Titanium and similar HTML5/JavaScript based hybrids.
-
Use false
if your user-base is guaranteed to use only desktop browsers,
or if your web site layout is totally unsuitable for mobile devices.
-
By providing the appropriate property in NumBox’s Setup Method. For example:
$('#creditcard').NumBox({type: 'ccard', autoScroll: true});
-
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);
This can be done with a simple HTML content tag on your page in one of two ways:
- A div with a data-role="content" attribute.
- 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');
|
---|---|
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:
- blur
- focus
- input
- keydown
- paste
- propertychange
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.
-
By providing the appropriate property in NumBox’s Setup Method. For example:
$('#creditcard').NumBox({type: 'ccard', onKeydown: 'fnMakeAClickingNoise'});
-
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.