1
0
Fork 0
mirror of https://github.com/jellyfin/jellyfin-web synced 2025-03-30 19:56:21 +00:00

update autoNumeric.js to 1.9.18

This commit is contained in:
Luke Pulverenti 2013-12-15 11:53:09 -05:00
parent f0a64f2f2e
commit 674e24fe3e

View file

@ -1,44 +1,42 @@
/** /**
* autoNumeric.js * autoNumeric.js
* @author: Bob Knothe * @author: Bob Knothe
* @author: Sokolov Yura aka funny_falcon * @author: Sokolov Yura aka funny_falcon
* @version: 1.9.6 - 2013-04-20 GMT 3:00 PM * @version: 1.9.18 - 2013-12-03 GMT 9:00 PM
* *
* Created by Robert J. Knothe on 2010-10-25. Please report any bug at http://www.decorplanit.com/plugin/ * Created by Robert J. Knothe on 2010-10-25. Please report any bugs to https://github.com/BobKnothe/autoNumeric
* Created by Sokolov Yura on 2010-11-07. http://github.com/funny_falcon * Created by Sokolov Yura on 2010-11-07
* *
* Copyright (c) 2011 Robert J. Knothe http://www.decorplanit.com/plugin/ * Copyright (c) 2011 Robert J. Knothe http://www.decorplanit.com/plugin/
* Copyright (c) 2011 Sokolov Yura aka funny_falcon *
* * The MIT License (http://www.opensource.org/licenses/mit-license.php)
* The MIT License (http://www.opensource.org/licenses/mit-license.php) *
* * Permission is hereby granted, free of charge, to any person
* Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation
* obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without
* files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use,
* restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell
* copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the
* copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following
* Software is furnished to do so, subject to the following * conditions:
* conditions: *
* * The above copyright notice and this permission notice shall be
* The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software.
* included in all copies or substantial portions of the Software. *
* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE.
* OTHER DEALINGS IN THE SOFTWARE. */
*/ (function ($) {
(function($) {
"use strict"; "use strict";
/**jslint browser: true*/ /*jslint browser: true*/
/**global jQuery*/ /*global jQuery: false*/
/** /* Cross browser routine for getting selected range/cursor position
* Cross browser routine for getting selected range/cursor position
*/ */
function getElementSelection(that) { function getElementSelection(that) {
var position = {}; var position = {};
@ -84,7 +82,7 @@
* k = option name example k=aNum * k = option name example k=aNum
* val = option value example val=0123456789 * val = option value example val=0123456789
*/ */
$.each(settings, function(k, val) { $.each(settings, function (k, val) {
if (typeof val === 'function') { if (typeof val === 'function') {
settings[k] = val($this, settings, k); settings[k] = val($this, settings, k);
} else if (typeof $this.autoNumeric[val] === 'function') { } else if (typeof $this.autoNumeric[val] === 'function') {
@ -95,7 +93,6 @@
} }
}); });
} }
function convertKeyToNumber(settings, key) { function convertKeyToNumber(settings, key) {
if (typeof (settings[key]) === 'string') { if (typeof (settings[key]) === 'string') {
settings[key] *= 1; settings[key] *= 1;
@ -103,12 +100,12 @@
} }
/** /**
* Preparing user defined options for further usage * Preparing user defined options for further usage
* merge them with defaults appropriatly * merge them with defaults appropriately
*/ */
function autoCode($this, settings) { function autoCode($this, settings) {
runCallbacks($this, settings); runCallbacks($this, settings);
settings.oEvent = null; settings.oEvent = null;
settings.tagList = ['DD', 'DT', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'LABEL', 'P', 'SPAN', 'TD', 'TH']; settings.tagList = ['B', 'CAPTION', 'CITE', 'CODE', 'DD', 'DEL', 'DIV', 'DFN', 'DT', 'EM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'INS', 'KDB', 'LABEL', 'LI', 'OUTPUT', 'P', 'Q', 'S', 'SAMPLE', 'SPAN', 'STRONG', 'TD', 'TH', 'U', 'VAR'];
var vmax = settings.vMax.toString().split('.'), var vmax = settings.vMax.toString().split('.'),
vmin = (!settings.vMin && settings.vMin !== 0) ? [] : settings.vMin.toString().split('.'); vmin = (!settings.vMin && settings.vMin !== 0) ? [] : settings.vMin.toString().split('.');
convertKeyToNumber(settings, 'vMax'); convertKeyToNumber(settings, 'vMax');
@ -233,19 +230,20 @@
return s; return s;
} }
/** /**
* function to handle numbers less than 0 that are stored in Exponential notaion ex: .0000001 stored as 1e-7 * function to handle numbers less than 0 that are stored in Exponential notation ex: .0000001 stored as 1e-7
*/ */
function checkValue(value) { function checkValue(value, settings) {
var decimal = value.indexOf('.'); var decimal = value.indexOf('.'),
checkSmall = +value;
if (decimal !== -1) { if (decimal !== -1) {
if (decimal === 1 && value.charAt(0) === '0') { if (checkSmall < 0.000001 && checkSmall > -1) {
value = +value; value = +value;
if (value < 0.000001 && value > 0) { if (value < 0.000001 && value > 0) {
value = (value + 1).toString(); value = (value + 10).toString();
value = value.substring(1); value = value.substring(1);
} }
if (value < 0 && value > -1) { if (value < 0 && value > -1) {
value = (value - 1).toString(); value = (value - 10).toString();
value = '-' + value.substring(2); value = '-' + value.substring(2);
} }
value = value.toString(); value = value.toString();
@ -261,7 +259,7 @@
} }
} }
} }
return value.replace(/^0*(\d)/, '$1'); return (settings.lZero === 'keep') ? value : value.replace(/^0*(\d)/, '$1');
} }
/** /**
* prepare real number to be converted to our format * prepare real number to be converted to our format
@ -310,7 +308,7 @@
*/ */
function autoGroup(iv, settings) { function autoGroup(iv, settings) {
iv = autoStrip(iv, settings); iv = autoStrip(iv, settings);
var testNeg = iv, var testNeg = iv.replace(',', '.'),
empty = checkEmpty(iv, settings, true); empty = checkEmpty(iv, settings, true);
if (empty !== null) { if (empty !== null) {
return empty; return empty;
@ -338,7 +336,7 @@
ivSplit[1] = ivSplit[1].substring(0, settings.mDec); ivSplit[1] = ivSplit[1].substring(0, settings.mDec);
} /** joins the whole number with the deciaml value */ } /** joins the whole number with the deciaml value */
iv = s + settings.aDec + ivSplit[1]; iv = s + settings.aDec + ivSplit[1];
} else { /** if whole numers only */ } else { /** if whole numbers only */
iv = s; iv = s;
} }
if (settings.aSign) { if (settings.aSign) {
@ -357,8 +355,8 @@
/** /**
* round number after setting by pasting or $().autoNumericSet() * round number after setting by pasting or $().autoNumericSet()
* private function for round the number * private function for round the number
* please note this handled as text - Javascript math function can return inaccurate values * please note this handled as text - JavaScript math function can return inaccurate values
* also this offers multiple rounding metods that are not easily accomplished in javascript * also this offers multiple rounding methods that are not easily accomplished in JavaScript
*/ */
function autoRound(iv, settings) { /** value to string */ function autoRound(iv, settings) { /** value to string */
iv = (iv === '') ? '0' : iv.toString(); iv = (iv === '') ? '0' : iv.toString();
@ -367,7 +365,7 @@
i = 0, i = 0,
nSign = '', nSign = '',
rDec = (typeof (settings.aPad) === 'boolean' || settings.aPad === null) ? (settings.aPad ? settings.mDec : 0) : +settings.aPad; rDec = (typeof (settings.aPad) === 'boolean' || settings.aPad === null) ? (settings.aPad ? settings.mDec : 0) : +settings.aPad;
var truncateZeros = function(ivRounded) { /** truncate not needed zeros */ var truncateZeros = function (ivRounded) { /** truncate not needed zeros */
var regex = rDec === 0 ? (/(\.[1-9]*)0*$/) : rDec === 1 ? (/(\.\d[1-9]*)0*$/) : new RegExp('(\\.\\d{' + rDec + '}[1-9]*)0*$'); var regex = rDec === 0 ? (/(\.[1-9]*)0*$/) : rDec === 1 ? (/(\.\d[1-9]*)0*$/) : new RegExp('(\\.\\d{' + rDec + '}[1-9]*)0*$');
ivRounded = ivRounded.replace(regex, '$1'); /** If there are no decimal places, we don't need a decimal point at the end */ ivRounded = ivRounded.replace(regex, '$1'); /** If there are no decimal places, we don't need a decimal point at the end */
if (rDec === 0) { if (rDec === 0) {
@ -388,9 +386,9 @@
if ((+iv > 0 && settings.lZero !== 'keep') || (iv.length > 0 && settings.lZero === 'allow')) { /** trims leading zero's if needed */ if ((+iv > 0 && settings.lZero !== 'keep') || (iv.length > 0 && settings.lZero === 'allow')) { /** trims leading zero's if needed */
iv = iv.replace(/^0*(\d)/, '$1'); iv = iv.replace(/^0*(\d)/, '$1');
} }
var dPos = iv.lastIndexOf('.'); /** virtual decimal position */ var dPos = iv.lastIndexOf('.'), /** virtual decimal position */
var vdPos = dPos === -1 ? iv.length - 1 : dPos; /** checks decimal places to determine if rounding is required */ vdPos = dPos === -1 ? iv.length - 1 : dPos, /** checks decimal places to determine if rounding is required */
var cDec = (iv.length - 1) - vdPos; /** check if no rounding is required */ cDec = (iv.length - 1) - vdPos; /** check if no rounding is required */
if (cDec <= settings.mDec) { if (cDec <= settings.mDec) {
ivRounded = iv; /** check if we need to pad with zeros */ ivRounded = iv; /** check if we need to pad with zeros */
if (cDec < rDec) { if (cDec < rDec) {
@ -409,18 +407,19 @@
} }
return nSign + ivRounded; return nSign + ivRounded;
} /** rounded length of the string after rounding */ } /** rounded length of the string after rounding */
var rLength = dPos + settings.mDec; /** test round */ var rLength = dPos + settings.mDec, /** test round */
var tRound = +iv.charAt(rLength + 1); tRound = +iv.charAt(rLength + 1),
var ivArray = iv.substring(0, rLength + 1).split(''); ivArray = iv.substring(0, rLength + 1).split(''),
var odd = (iv.charAt(rLength) === '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2); odd = (iv.charAt(rLength) === '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2);
if ((tRound > 4 && settings.mRound === 'S') || (tRound > 4 && settings.mRound === 'A' && nSign === '') || (tRound > 5 && settings.mRound === 'A' && nSign === '-') || (tRound > 5 && settings.mRound === 's') || (tRound > 5 && settings.mRound === 'a' && nSign === '') || (tRound > 4 && settings.mRound === 'a' && nSign === '-') || (tRound > 5 && settings.mRound === 'B') || (tRound === 5 && settings.mRound === 'B' && odd === 1) || (tRound > 0 && settings.mRound === 'C' && nSign === '') || (tRound > 0 && settings.mRound === 'F' && nSign === '-') || (tRound > 0 && settings.mRound === 'U')) { if ((tRound > 4 && settings.mRound === 'S') || (tRound > 4 && settings.mRound === 'A' && nSign === '') || (tRound > 5 && settings.mRound === 'A' && nSign === '-') || (tRound > 5 && settings.mRound === 's') || (tRound > 5 && settings.mRound === 'a' && nSign === '') || (tRound > 4 && settings.mRound === 'a' && nSign === '-') || (tRound > 5 && settings.mRound === 'B') || (tRound === 5 && settings.mRound === 'B' && odd === 1) || (tRound > 0 && settings.mRound === 'C' && nSign === '') || (tRound > 0 && settings.mRound === 'F' && nSign === '-') || (tRound > 0 && settings.mRound === 'U')) {
/** Round up the last digit if required, and continue until no more 9's are found */ /** Round up the last digit if required, and continue until no more 9's are found */
for (i = (ivArray.length - 1); i >= 0; i -= 1) { for (i = (ivArray.length - 1) ; i >= 0; i -= 1) {
if (ivArray[i] !== '.') { if (ivArray[i] !== '.') {
ivArray[i] = +ivArray[i] + 1; ivArray[i] = +ivArray[i] + 1;
if (ivArray[i] < 10) { if (ivArray[i] < 10) {
break; break;
} else if (i > 0) { }
if (i > 0) {
ivArray[i] = '0'; ivArray[i] = '0';
} }
} }
@ -428,7 +427,7 @@
} /** Reconstruct the string, converting any 10's to 0's */ } /** Reconstruct the string, converting any 10's to 0's */
ivArray = ivArray.slice(0, rLength + 1); ivArray = ivArray.slice(0, rLength + 1);
ivRounded = truncateZeros(ivArray.join('')); /** return rounded value */ ivRounded = truncateZeros(ivArray.join('')); /** return rounded value */
return nSign + ivRounded; return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
} }
/** /**
* Holder object for field properties * Holder object for field properties
@ -442,13 +441,13 @@
this.value = that.value; this.value = that.value;
} }
AutoNumericHolder.prototype = { AutoNumericHolder.prototype = {
init: function(e) { init: function (e) {
this.value = this.that.value; this.value = this.that.value;
this.settingsClone = autoCode(this.$that, this.settings); this.settingsClone = autoCode(this.$that, this.settings);
this.ctrlKey = e.ctrlKey; this.ctrlKey = e.ctrlKey;
this.cmdKey = e.metaKey; this.cmdKey = e.metaKey;
this.shiftKey = e.shiftKey; this.shiftKey = e.shiftKey;
this.selection = getElementSelection(this.that); /** keypress event overwrites meaningfull value of e.keyCode */ this.selection = getElementSelection(this.that); /** keypress event overwrites meaningful value of e.keyCode */
if (e.type === 'keydown' || e.type === 'keyup') { if (e.type === 'keydown' || e.type === 'keyup') {
this.kdCode = e.keyCode; this.kdCode = e.keyCode;
} }
@ -456,7 +455,7 @@
this.processed = false; this.processed = false;
this.formatted = false; this.formatted = false;
}, },
setSelection: function(start, end, setReal) { setSelection: function (start, end, setReal) {
start = Math.max(start, 0); start = Math.max(start, 0);
end = Math.min(end, this.that.value.length); end = Math.min(end, this.that.value.length);
this.selection = { this.selection = {
@ -468,16 +467,16 @@
setElementSelection(this.that, start, end); setElementSelection(this.that, start, end);
} }
}, },
setPosition: function(pos, setReal) { setPosition: function (pos, setReal) {
this.setSelection(pos, pos, setReal); this.setSelection(pos, pos, setReal);
}, },
getBeforeAfter: function() { getBeforeAfter: function () {
var value = this.value; var value = this.value,
var left = value.substring(0, this.selection.start); left = value.substring(0, this.selection.start),
var right = value.substring(this.selection.end, value.length); right = value.substring(this.selection.end, value.length);
return [left, right]; return [left, right];
}, },
getBeforeAfterStriped: function() { getBeforeAfterStriped: function () {
var parts = this.getBeforeAfter(); var parts = this.getBeforeAfter();
parts[0] = autoStrip(parts[0], this.settingsClone); parts[0] = autoStrip(parts[0], this.settingsClone);
parts[1] = autoStrip(parts[1], this.settingsClone); parts[1] = autoStrip(parts[1], this.settingsClone);
@ -486,7 +485,7 @@
/** /**
* strip parts from excess characters and leading zeroes * strip parts from excess characters and leading zeroes
*/ */
normalizeParts: function(left, right) { normalizeParts: function (left, right) {
var settingsClone = this.settingsClone; var settingsClone = this.settingsClone;
right = autoStrip(right, settingsClone); /** if right is not empty and first character is not aDec, */ right = autoStrip(right, settingsClone); /** if right is not empty and first character is not aDec, */
/** we could strip all zeros, otherwise only leading */ /** we could strip all zeros, otherwise only leading */
@ -513,11 +512,11 @@
/** /**
* set part of number to value keeping position of cursor * set part of number to value keeping position of cursor
*/ */
setValueParts: function(left, right) { setValueParts: function (left, right) {
var settingsClone = this.settingsClone; var settingsClone = this.settingsClone,
var parts = this.normalizeParts(left, right); parts = this.normalizeParts(left, right),
var new_value = parts.join(''); new_value = parts.join(''),
var position = parts[0].length; position = parts[0].length;
if (autoCheck(new_value, settingsClone)) { if (autoCheck(new_value, settingsClone)) {
new_value = truncateDecimal(new_value, settingsClone.aDec, settingsClone.mDec); new_value = truncateDecimal(new_value, settingsClone.aDec, settingsClone.mDec);
if (position > new_value.length) { if (position > new_value.length) {
@ -533,7 +532,7 @@
* helper function for expandSelectionOnSign * helper function for expandSelectionOnSign
* returns sign position of a formatted value * returns sign position of a formatted value
*/ */
signPosition: function() { signPosition: function () {
var settingsClone = this.settingsClone, var settingsClone = this.settingsClone,
aSign = settingsClone.aSign, aSign = settingsClone.aSign,
that = this.that; that = this.that;
@ -550,11 +549,11 @@
}, },
/** /**
* expands selection to cover whole sign * expands selection to cover whole sign
* prevents partial deletion/copying/overwritting of a sign * prevents partial deletion/copying/overwriting of a sign
*/ */
expandSelectionOnSign: function(setReal) { expandSelectionOnSign: function (setReal) {
var sign_position = this.signPosition(); var sign_position = this.signPosition(),
var selection = this.selection; selection = this.selection;
if (selection.start < sign_position[1] && selection.end > sign_position[0]) { /** if selection catches something except sign and catches only space from sign */ if (selection.start < sign_position[1] && selection.end > sign_position[0]) { /** if selection catches something except sign and catches only space from sign */
if ((selection.start < sign_position[0] || selection.end > sign_position[1]) && this.value.substring(Math.max(selection.start, sign_position[0]), Math.min(selection.end, sign_position[1])).match(/^\s*$/)) { /** then select without empty space */ if ((selection.start < sign_position[0] || selection.end > sign_position[1]) && this.value.substring(Math.max(selection.start, sign_position[0]), Math.min(selection.end, sign_position[1])).match(/^\s*$/)) { /** then select without empty space */
if (selection.start < sign_position[0]) { if (selection.start < sign_position[0]) {
@ -570,10 +569,10 @@
/** /**
* try to strip pasted value to digits * try to strip pasted value to digits
*/ */
checkPaste: function() { checkPaste: function () {
if (this.valuePartsBeforePaste !== undefined) { if (this.valuePartsBeforePaste !== undefined) {
var parts = this.getBeforeAfter(); var parts = this.getBeforeAfter(),
var oldParts = this.valuePartsBeforePaste; oldParts = this.valuePartsBeforePaste;
delete this.valuePartsBeforePaste; /** try to strip pasted value first */ delete this.valuePartsBeforePaste; /** try to strip pasted value first */
parts[0] = parts[0].substr(0, oldParts[0].length) + autoStrip(parts[0].substr(oldParts[0].length), this.settingsClone); parts[0] = parts[0].substr(0, oldParts[0].length) + autoStrip(parts[0].substr(oldParts[0].length), this.settingsClone);
if (!this.setValueParts(parts[0], parts[1])) { if (!this.setValueParts(parts[0], parts[1])) {
@ -586,8 +585,12 @@
* process pasting, cursor moving and skipping of not interesting keys * process pasting, cursor moving and skipping of not interesting keys
* if returns true, futher processing is not performed * if returns true, futher processing is not performed
*/ */
skipAllways: function(e) { skipAllways: function (e) {
var kdCode = this.kdCode, which = this.which, ctrlKey = this.ctrlKey, cmdKey = this.cmdKey, shiftKey = this.shiftKey; /** catch the ctrl up on ctrl-v */ var kdCode = this.kdCode,
which = this.which,
ctrlKey = this.ctrlKey,
cmdKey = this.cmdKey,
shiftKey = this.shiftKey; /** catch the ctrl up on ctrl-v */
if (((ctrlKey || cmdKey) && e.type === 'keyup' && this.valuePartsBeforePaste !== undefined) || (shiftKey && kdCode === 45)) { if (((ctrlKey || cmdKey) && e.type === 'keyup' && this.valuePartsBeforePaste !== undefined) || (shiftKey && kdCode === 45)) {
this.checkPaste(); this.checkPaste();
return false; return false;
@ -626,7 +629,7 @@
if (e.type === 'keydown' && aSep && !this.shiftKey) { if (e.type === 'keydown' && aSep && !this.shiftKey) {
if (kdCode === 37 && value.charAt(start - 2) === aSep) { if (kdCode === 37 && value.charAt(start - 2) === aSep) {
this.setPosition(start - 1); this.setPosition(start - 1);
} else if (kdCode === 39 && value.charAt(start) === aSep) { } else if (kdCode === 39 && value.charAt(start + 1) === aSep) {
this.setPosition(start + 1); this.setPosition(start + 1);
} }
} }
@ -641,7 +644,7 @@
* process deletion of characters * process deletion of characters
* returns true if processing performed * returns true if processing performed
*/ */
processAllways: function() { processAllways: function () {
var parts; /** process backspace or delete */ var parts; /** process backspace or delete */
if (this.kdCode === 8 || this.kdCode === 46) { if (this.kdCode === 8 || this.kdCode === 46) {
if (!this.selection.length) { if (!this.selection.length) {
@ -665,12 +668,12 @@
* process insertion of characters * process insertion of characters
* returns true if processing performed * returns true if processing performed
*/ */
processKeypress: function() { processKeypress: function () {
var settingsClone = this.settingsClone; var settingsClone = this.settingsClone,
var cCode = String.fromCharCode(this.which); cCode = String.fromCharCode(this.which),
var parts = this.getBeforeAfterStriped(); parts = this.getBeforeAfterStriped(),
var left = parts[0], left = parts[0],
right = parts[1]; /** start rules when the decimal charactor key is pressed */ right = parts[1]; /** start rules when the decimal character key is pressed */
/** always use numeric pad dot to insert decimal separator */ /** always use numeric pad dot to insert decimal separator */
if (cCode === settingsClone.aDec || (settingsClone.altDec && cCode === settingsClone.altDec) || ((cCode === '.' || cCode === ',') && this.kdCode === 110)) { /** do not allow decimal character if no decimal part allowed */ if (cCode === settingsClone.aDec || (settingsClone.altDec && cCode === settingsClone.altDec) || ((cCode === '.' || cCode === ',') && this.kdCode === 110)) { /** do not allow decimal character if no decimal part allowed */
if (!settingsClone.mDec || !settingsClone.aDec) { if (!settingsClone.mDec || !settingsClone.aDec) {
@ -691,10 +694,11 @@
this.setValueParts(left + settingsClone.aDec, right); this.setValueParts(left + settingsClone.aDec, right);
return true; return true;
} /** start rule on negative sign */ } /** start rule on negative sign */
if (cCode === '-' || cCode === '+') { /** prevent minus if not allowed */ if (cCode === '-' || cCode === '+') { /** prevent minus if not allowed */
if (!settingsClone.aNeg) { if (!settingsClone.aNeg) {
return true; return true;
} /** carret is always after minus */ } /** caret is always after minus */
if (left === '' && right.indexOf(settingsClone.aNeg) > -1) { if (left === '' && right.indexOf(settingsClone.aNeg) > -1) {
left = settingsClone.aNeg; left = settingsClone.aNeg;
right = right.substring(1, right.length); right = right.substring(1, right.length);
@ -723,10 +727,10 @@
/** /**
* formatting of just processed value with keeping of cursor position * formatting of just processed value with keeping of cursor position
*/ */
formatQuick: function() { formatQuick: function () {
var settingsClone = this.settingsClone; var settingsClone = this.settingsClone,
var parts = this.getBeforeAfterStriped(); parts = this.getBeforeAfterStriped(),
var leftLength = this.value; leftLength = this.value;
if ((settingsClone.aSep === '' || (settingsClone.aSep !== '' && leftLength.indexOf(settingsClone.aSep) === -1)) && (settingsClone.aSign === '' || (settingsClone.aSign !== '' && leftLength.indexOf(settingsClone.aSign) === -1))) { if ((settingsClone.aSep === '' || (settingsClone.aSep !== '' && leftLength.indexOf(settingsClone.aSep) === -1)) && (settingsClone.aSign === '' || (settingsClone.aSign !== '' && leftLength.indexOf(settingsClone.aSign) === -1))) {
var subParts = [], var subParts = [],
nSign = ''; nSign = '';
@ -741,12 +745,12 @@
} }
parts[0] = nSign + parts[0]; parts[0] = nSign + parts[0];
} }
var value = autoGroup(this.value, this.settingsClone); var value = autoGroup(this.value, this.settingsClone),
var position = value.length; position = value.length;
if (value) { if (value) {
/** prepare regexp which searches for cursor position from unformatted left part */ /** prepare regexp which searches for cursor position from unformatted left part */
var left_ar = parts[0].split(''); var left_ar = parts[0].split(''),
var i = 0; i = 0;
for (i; i < left_ar.length; i += 1) { /** thanks Peter Kovari */ for (i; i < left_ar.length; i += 1) { /** thanks Peter Kovari */
if (!left_ar[i].match('\\d')) { if (!left_ar[i].match('\\d')) {
left_ar[i] = '\\' + left_ar[i]; left_ar[i] = '\\' + left_ar[i];
@ -798,12 +802,12 @@
return holder; return holder;
} }
var methods = { var methods = {
init: function(options) { init: function (options) {
return this.each(function() { return this.each(function () {
var $this = $(this); var $this = $(this),
var settings = $this.data('autoNumeric'); /** attempt to grab 'autoNumeric' settings, if they don't exist returns "undefined". */ settings = $this.data('autoNumeric'), /** attempt to grab 'autoNumeric' settings, if they don't exist returns "undefined". */
var tagData = $this.data(); /** attempt to grab HTML5 data, if they don't exist we'll get "undefined".*/ tagData = $this.data(); /** attempt to grab HTML5 data, if they don't exist we'll get "undefined".*/
if (typeof settings !== 'object') { /** If we could't grab settings, create them from defaults and passed options. */ if (typeof settings !== 'object') { /** If we couldn't grab settings, create them from defaults and passed options. */
var defaults = { var defaults = {
/** allowed numeric values /** allowed numeric values
* please do not modify * please do not modify
@ -847,13 +851,13 @@
* value must be enclosed in quotes and use the period for the decimal point * value must be enclosed in quotes and use the period for the decimal point
* value must be larger than vMin * value must be larger than vMin
*/ */
vMax: '999999999999.99', vMax: '999999999.99',
/** minimum possible value /** minimum possible value
* value must be enclosed in quotes and use the period for the decimal point * value must be enclosed in quotes and use the period for the decimal point
* value must be smaller than vMax * value must be smaller than vMax
*/ */
vMin: '0.00', vMin: '0.00',
/** max number of decimal places = used to overide deciaml places set by the vMin & vMax values /** max number of decimal places = used to override decimal places set by the vMin & vMax values
* value must be enclosed in quotes example mDec: '3', * value must be enclosed in quotes example mDec: '3',
* This can also set the value via a call back function mDec: 'css:# * This can also set the value via a call back function mDec: 'css:#
*/ */
@ -865,7 +869,7 @@
* mRound: 'a', Round-Half-Down Asymmetric (lower case a) * mRound: 'a', Round-Half-Down Asymmetric (lower case a)
* mRound: 'B', Round-Half-Even "Bankers Rounding" * mRound: 'B', Round-Half-Even "Bankers Rounding"
* mRound: 'U', Round Up "Round-Away-From-Zero" * mRound: 'U', Round Up "Round-Away-From-Zero"
* mRound: 'D', Round Down "Round-Toward-Zero" - same as trancate * mRound: 'D', Round Down "Round-Toward-Zero" - same as truncate
* mRound: 'C', Round to Ceiling "Toward Positive Infinity" * mRound: 'C', Round to Ceiling "Toward Positive Infinity"
* mRound: 'F', Round to Floor "Toward Negative Infinity" * mRound: 'F', Round to Floor "Toward Negative Infinity"
*/ */
@ -895,50 +899,54 @@
*/ */
lZero: 'allow', lZero: 'allow',
/** determine if the default value will be formatted on page ready. /** determine if the default value will be formatted on page ready.
* true = atomatically formats the default value on page ready * true = automatically formats the default value on page ready
* false = will not format the default value * false = will not format the default value
*/ */
aForm: true, aForm: true,
/** future use */ /** future use */
onSomeEvent: function() {} onSomeEvent: function () { }
}; };
settings = $.extend({}, defaults, tagData, options); /** Merge defaults, tagData and options */ settings = $.extend({}, defaults, tagData, options); /** Merge defaults, tagData and options */
if (settings.aDec === settings.aSep) { if (settings.aDec === settings.aSep) {
$.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand seperater aSep: '" + settings.aSep + "' are the same character"); $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
return this;
}
if ($.inArray($this.prop('tagName'), settings.tagList) !== -1) {
$.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()");
return this; return this;
} }
$this.data('autoNumeric', settings); /** Save our new settings */ $this.data('autoNumeric', settings); /** Save our new settings */
} else { } else {
return this; return this;
} }
settings.lastSetValue = '';
settings.runOnce = false;
var holder = getHolder($this, settings); var holder = getHolder($this, settings);
if (settings.runOnce === undefined && settings.aForm && ($this[0].value || $this.text() !== '')) { if ($.inArray($this.prop('tagName'), settings.tagList) === -1 && $this.prop('tagName') !== 'INPUT') {
if ($this.is('input[type=text], input[type=hidden], input:not([type])')) { /**added hidden type */ $.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()");
if (settings.nBracket !== null && ($this[0].value || settings.wEmpty !== 'empty')) { /** routine to handle page refresh */ return this;
settings.oEvent = "pageLoad";
$this[0].value = negativeBracket($this[0].value, settings.nBracket, settings.oEvent);
$this[0].value = autoStrip($this[0].value, settings);
} }
if ($this[0].value !== $($this[0]).attr("value")) { if (settings.runOnce === false && settings.aForm) {/** routine to format default value on page load */
$this.autoNumeric('set', autoStrip($this.val(), settings)); if ($this.is('input[type=text], input[type=hidden], input:not([type])')) {
} else { var setValue = true;
if ($this[0].value === '' && settings.wEmpty === 'empty') {
$this[0].value = '';
setValue = false;
}
if ($this[0].value === '' && settings.wEmpty === 'sign') {
$this[0].value = settings.aSign;
setValue = false;
}
if (setValue) {
$this.autoNumeric('set', $this.val()); $this.autoNumeric('set', $this.val());
} }
} }
if ($.inArray($this.prop('tagName'), settings.tagList) !== -1) { if ($.inArray($this.prop('tagName'), settings.tagList) !== -1 && $this.text() !== '') {
$this.autoNumeric('set', $this.text()); $this.autoNumeric('set', $this.text());
} }
} }
settings.runOnce = true; settings.runOnce = true;
if ($this.is('input[type=text], input[type=hidden], input:not([type])')) { /**added hidden type */ if ($this.is('input[type=text], input[type=hidden], input:not([type])')) { /**added hidden type */
$this.bind('keydown.autoNumeric', function(e) { $this.on('keydown.autoNumeric', function (e) {
holder = getHolder($this); holder = getHolder($this);
if (holder.settings.aDec === holder.settings.aSep) { if (holder.settings.aDec === holder.settings.aSep) {
$.error("autoNumeric will not function properly when the decimal character aDec: '" + holder.settings.aDec + "' and thousand seperater aSep: '" + holder.settings.aSep + "' are the same character"); $.error("autoNumeric will not function properly when the decimal character aDec: '" + holder.settings.aDec + "' and thousand separator aSep: '" + holder.settings.aSep + "' are the same character");
return this; return this;
} }
if (holder.that.readOnly) { if (holder.that.readOnly) {
@ -965,8 +973,9 @@
holder.formatted = false; holder.formatted = false;
return true; return true;
}); });
$this.bind('keypress.autoNumeric', function(e) { $this.on('keypress.autoNumeric', function (e) {
var holder = getHolder($this), processed = holder.processed; var holder = getHolder($this),
processed = holder.processed;
holder.init(e); holder.init(e);
holder.settings.oEvent = 'keypress'; holder.settings.oEvent = 'keypress';
if (holder.skipAllways(e)) { if (holder.skipAllways(e)) {
@ -982,15 +991,21 @@
return false; return false;
} }
holder.formatted = false; holder.formatted = false;
}); });
$this.bind('keyup.autoNumeric', function(e) { $this.on('keyup.autoNumeric', function (e) {
var holder = getHolder($this); var holder = getHolder($this);
holder.init(e); holder.init(e);
holder.settings.oEvent = 'keyup'; holder.settings.oEvent = 'keyup';
var skip = holder.skipAllways(e); var skip = holder.skipAllways(e);
holder.kdCode = 0; holder.kdCode = 0;
delete holder.valuePartsBeforePaste; delete holder.valuePartsBeforePaste;
if ($this[0].value === holder.settings.aSign) { /** added to properly place the caret when only the currency is present */
if (holder.settings.pSign === 's') {
setElementSelection(this, 0, 0);
} else {
setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
}
}
if (skip) { if (skip) {
return true; return true;
} }
@ -1001,7 +1016,7 @@
holder.formatQuick(); holder.formatQuick();
} }
}); });
$this.bind('focusin.autoNumeric', function() { $this.on('focusin.autoNumeric', function () {
var holder = getHolder($this); var holder = getHolder($this);
holder.settingsClone.oEvent = 'focusin'; holder.settingsClone.oEvent = 'focusin';
if (holder.settingsClone.nBracket !== null) { if (holder.settingsClone.nBracket !== null) {
@ -1012,9 +1027,14 @@
var onempty = checkEmpty(holder.inVal, holder.settingsClone, true); var onempty = checkEmpty(holder.inVal, holder.settingsClone, true);
if (onempty !== null) { if (onempty !== null) {
$this.val(onempty); $this.val(onempty);
if (holder.settings.pSign === 's') {
setElementSelection(this, 0, 0);
} else {
setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
}
} }
}); });
$this.bind('focusout.autoNumeric', function() { $this.on('focusout.autoNumeric', function () {
var holder = getHolder($this), var holder = getHolder($this),
settingsClone = holder.settingsClone, settingsClone = holder.settingsClone,
value = $this.val(), value = $this.val(),
@ -1055,16 +1075,16 @@
}); });
}, },
/** method to remove settings and stop autoNumeric() */ /** method to remove settings and stop autoNumeric() */
destroy: function() { destroy: function () {
return $(this).each(function() { return $(this).each(function () {
var $this = $(this); var $this = $(this);
$this.unbind('.autoNumeric'); $this.off('.autoNumeric');
$this.removeData('autoNumeric'); $this.removeData('autoNumeric');
}); });
}, },
/** method to update settings - can call as many times */ /** method to update settings - can call as many times */
update: function(options) { update: function (options) {
return $(this).each(function() { return $(this).each(function () {
var $this = autoGet($(this)), var $this = autoGet($(this)),
settings = $this.data('autoNumeric'); settings = $this.data('autoNumeric');
if (typeof settings !== 'object') { if (typeof settings !== 'object') {
@ -1075,7 +1095,7 @@
settings = $.extend(settings, options); settings = $.extend(settings, options);
getHolder($this, settings, true); getHolder($this, settings, true);
if (settings.aDec === settings.aSep) { if (settings.aDec === settings.aSep) {
$.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand seperater aSep: '" + settings.aSep + "' are the same character"); $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
return this; return this;
} }
$this.data('autoNumeric', settings); $this.data('autoNumeric', settings);
@ -1085,20 +1105,32 @@
return; return;
}); });
}, },
/** returns a formated strings for "input:text" fields Uses jQuery's .val() method*/ /** returns a formatted strings for "input:text" fields Uses jQuery's .val() method*/
set: function(valueIn) { set: function (valueIn) {
return $(this).each(function() { return $(this).each(function () {
var $this = autoGet($(this)), settings = $this.data('autoNumeric'), value = valueIn.toString(); var $this = autoGet($(this)),
settings = $this.data('autoNumeric'),
value = valueIn.toString(),
testValue = valueIn.toString();
if (typeof settings !== 'object') { if (typeof settings !== 'object') {
$.error("You must initialize autoNumeric('init', {options}) prior to calling the 'set' method"); $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'set' method");
return this; return this;
} }
/** allows locale decimal separator to be a comma */
if ((testValue === $this.attr('value') || testValue === $this.text()) && settings.runOnce === false) {
value = value.replace(',', '.');
}
/** routine to handle page re-load from back button */
if (testValue !== $this.attr('value') && $this.prop('tagName') === 'INPUT' && settings.runOnce === false) {
value = autoStrip(value, settings);
}
/** returns a empty string if the value being 'set' contains non-numeric characters and or more than decimal point (full stop) and will not be formatted */ /** returns a empty string if the value being 'set' contains non-numeric characters and or more than decimal point (full stop) and will not be formatted */
if (!$.isNumeric(+value)) { if (!$.isNumeric(+value)) {
return ''; return '';
} }
value = checkValue(value); value = checkValue(value, settings);
settings.oEvent = 'set'; settings.oEvent = 'set';
settings.lastSetValue = value; /** saves the unrounded value from the set method - $('selector').data('autoNumeric').lastSetValue; - helpful when you need to change the rounding accuracy*/
value.toString(); value.toString();
if (value !== '') { if (value !== '') {
value = autoRound(value, settings); value = autoRound(value, settings);
@ -1118,8 +1150,8 @@
return false; return false;
}); });
}, },
/** method to get the unformated value from a specific input field, returns a numeric value */ /** method to get the unformatted value from a specific input field, returns a numeric value */
get: function() { get: function () {
var $this = autoGet($(this)), var $this = autoGet($(this)),
settings = $this.data('autoNumeric'); settings = $this.data('autoNumeric');
if (typeof settings !== 'object') { if (typeof settings !== 'object') {
@ -1137,7 +1169,7 @@
$.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()"); $.error("The <" + $this.prop('tagName') + "> is not supported by autoNumeric()");
return false; return false;
} }
if ((getValue === '' && settings.wEmpty === 'empty') || (getValue === settings.aSign && settings.wEmpty === 'sign')) { if ((getValue === '' && settings.wEmpty === 'empty') || (getValue === settings.aSign && (settings.wEmpty === 'sign' || settings.wEmpty === 'empty'))) {
return ''; return '';
} }
if (settings.nBracket !== null && getValue !== '') { if (settings.nBracket !== null && getValue !== '') {
@ -1153,11 +1185,11 @@
if (settings.lZero === 'keep') { if (settings.lZero === 'keep') {
return getValue; return getValue;
} }
getValue = checkValue(getValue); getValue = checkValue(getValue, settings);
return getValue; /** returned Numeric String */ return getValue; /** returned Numeric String */
}, },
/** method to get the unformated value from multiple fields */ /** method to get the unformatted value from multiple fields */
getString: function() { getString: function () {
var isAutoNumeric = false, var isAutoNumeric = false,
$this = autoGet($(this)), $this = autoGet($(this)),
str = $this.serialize(), str = $this.serialize(),
@ -1180,12 +1212,12 @@
$.error("You must initialize autoNumeric('init', {options}) prior to calling the 'getString' method"); $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'getString' method");
return this; return this;
}, },
/** method to get the unformated value from multiple fields */ /** method to get the unformatted value from multiple fields */
getArray: function() { getArray: function () {
var isAutoNumeric = false, var isAutoNumeric = false,
$this = autoGet($(this)), $this = autoGet($(this)),
formFields = $this.serializeArray(); formFields = $this.serializeArray();
$.each(formFields, function(i, field) { $.each(formFields, function (i, field) {
var settings = $('*[name="' + decodeURIComponent(field.name) + '"]').data('autoNumeric'); var settings = $('*[name="' + decodeURIComponent(field.name) + '"]').data('autoNumeric');
if (typeof settings === 'object') { if (typeof settings === 'object') {
if (field.value !== '' && $('*[name="' + decodeURIComponent(field.name) + '"]').data('autoNumeric') !== undefined) { if (field.value !== '' && $('*[name="' + decodeURIComponent(field.name) + '"]').data('autoNumeric') !== undefined) {
@ -1201,12 +1233,12 @@
return this; return this;
}, },
/** returns the settings object for those who need to look under the hood */ /** returns the settings object for those who need to look under the hood */
getSettings: function() { getSettings: function () {
var $this = autoGet($(this)); var $this = autoGet($(this));
return $this.eq(0).data('autoNumeric'); return $this.eq(0).data('autoNumeric');
} }
}; };
$.fn.autoNumeric = function(method) { $.fn.autoNumeric = function (method) {
if (methods[method]) { if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} }