Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autoNumeric.js 69KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. /**
  2. * autoNumeric.js
  3. * @author: Bob Knothe
  4. * @author: Sokolov Yura
  5. * @version: 1.9.39 - 2015-07-17 GMT 5:00 PM / 19:00
  6. *
  7. * Created by Robert J. Knothe on 2010-10-25. Please report any bugs to https://github.com/BobKnothe/autoNumeric
  8. * Contributor by Sokolov Yura on 2010-11-07
  9. *
  10. * Copyright (c) 2011 Robert J. Knothe http://www.decorplanit.com/plugin/
  11. *
  12. * The MIT License (http://www.opensource.org/licenses/mit-license.php)
  13. *
  14. * Permission is hereby granted, free of charge, to any person
  15. * obtaining a copy of this software and associated documentation
  16. * files (the "Software"), to deal in the Software without
  17. * restriction, including without limitation the rights to use,
  18. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  19. * copies of the Software, and to permit persons to whom the
  20. * Software is furnished To Do so, subject to the following
  21. * conditions:
  22. *
  23. * The above copyright notice and this permission notice shall be
  24. * included in all copies or substantial portions of the Software.
  25. *
  26. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  28. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  30. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  31. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  32. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  33. * OTHER DEALINGS IN THE SOFTWARE.
  34. */
  35. (function ($) {
  36. "use strict";
  37. /*jslint browser: true*/
  38. /*global jQuery: false*/
  39. /*Cross browser routine for getting selected range/cursor position
  40. */
  41. /**
  42. * Cross browser routine for getting selected range/cursor position
  43. */
  44. function getElementSelection(that) {
  45. var position = {};
  46. if (that.selectionStart === undefined) {
  47. that.focus();
  48. var select = document.selection.createRange();
  49. position.length = select.text.length;
  50. select.moveStart('character', -that.value.length);
  51. position.end = select.text.length;
  52. position.start = position.end - position.length;
  53. } else {
  54. position.start = that.selectionStart;
  55. position.end = that.selectionEnd;
  56. position.length = position.end - position.start;
  57. }
  58. return position;
  59. }
  60. /**
  61. * Cross browser routine for setting selected range/cursor position
  62. */
  63. function setElementSelection(that, start, end) {
  64. if (that.selectionStart === undefined) {
  65. that.focus();
  66. var r = that.createTextRange();
  67. r.collapse(true);
  68. r.moveEnd('character', end);
  69. r.moveStart('character', start);
  70. r.select();
  71. } else {
  72. that.selectionStart = start;
  73. that.selectionEnd = end;
  74. }
  75. }
  76. /**
  77. * run callbacks in parameters if any
  78. * any parameter could be a callback:
  79. * - a function, which invoked with jQuery element, parameters and this parameter name and returns parameter value
  80. * - a name of function, attached to $(selector).autoNumeric.functionName(){} - which was called previously
  81. */
  82. function runCallbacks($this, settings) {
  83. /**
  84. * loops through the settings object (option array) to find the following
  85. * k = option name example k=aNum
  86. * val = option value example val=0123456789
  87. */
  88. $.each(settings, function (k, val) {
  89. if (typeof val === 'function') {
  90. settings[k] = val($this, settings, k);
  91. } else if (typeof $this.autoNumeric[val] === 'function') {
  92. /**
  93. * calls the attached function from the html5 data example: data-a-sign="functionName"
  94. */
  95. settings[k] = $this.autoNumeric[val]($this, settings, k);
  96. }
  97. });
  98. }
  99. /**
  100. * Converts the vMin, vMax & mDec string to numeric value
  101. */
  102. function convertKeyToNumber(settings, key) {
  103. if (typeof (settings[key]) === 'string') {
  104. settings[key] *= 1;
  105. }
  106. }
  107. /**
  108. * Preparing user defined options for further usage
  109. * merge them with defaults appropriately
  110. */
  111. function autoCode($this, settings) {
  112. runCallbacks($this, settings);
  113. 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'];
  114. var vmax = settings.vMax.toString().split('.'),
  115. vmin = (!settings.vMin && settings.vMin !== 0) ? [] : settings.vMin.toString().split('.');
  116. convertKeyToNumber(settings, 'vMax');
  117. convertKeyToNumber(settings, 'vMin');
  118. convertKeyToNumber(settings, 'mDec'); /** set mDec if not defined by user */
  119. settings.mDec = (settings.mRound === 'CHF') ? '2' : settings.mDec;
  120. settings.allowLeading = true;
  121. settings.aNeg = settings.vMin < 0 ? '-' : '';
  122. vmax[0] = vmax[0].replace('-', '');
  123. vmin[0] = vmin[0].replace('-', '');
  124. settings.mInt = Math.max(vmax[0].length, vmin[0].length, 1);
  125. if (settings.mDec === null) {
  126. var vmaxLength = 0,
  127. vminLength = 0;
  128. if (vmax[1]) {
  129. vmaxLength = vmax[1].length;
  130. }
  131. if (vmin[1]) {
  132. vminLength = vmin[1].length;
  133. }
  134. settings.mDec = Math.max(vmaxLength, vminLength);
  135. } /** set alternative decimal separator key */
  136. if (settings.altDec === null && settings.mDec > 0) {
  137. if (settings.aDec === '.' && settings.aSep !== ',') {
  138. settings.altDec = ',';
  139. } else if (settings.aDec === ',' && settings.aSep !== '.') {
  140. settings.altDec = '.';
  141. }
  142. }
  143. /** cache regexps for autoStrip */
  144. var aNegReg = settings.aNeg ? '([-\\' + settings.aNeg + ']?)' : '(-?)';
  145. settings.aNegRegAutoStrip = aNegReg;
  146. settings.skipFirstAutoStrip = new RegExp(aNegReg + '[^-' + (settings.aNeg ? '\\' + settings.aNeg : '') + '\\' + settings.aDec + '\\d]' + '.*?(\\d|\\' + settings.aDec + '\\d)');
  147. settings.skipLastAutoStrip = new RegExp('(\\d\\' + settings.aDec + '?)[^\\' + settings.aDec + '\\d]\\D*$');
  148. var allowed = '-' + settings.aNum + '\\' + settings.aDec;
  149. settings.allowedAutoStrip = new RegExp('[^' + allowed + ']', 'gi');
  150. settings.numRegAutoStrip = new RegExp(aNegReg + '(?:\\' + settings.aDec + '?(\\d+\\' + settings.aDec + '\\d+)|(\\d*(?:\\' + settings.aDec + '\\d*)?))');
  151. return settings;
  152. }
  153. /**
  154. * strips all unwanted characters and leave only a number alert
  155. */
  156. function autoStrip(s, settings, strip_zero) {
  157. if (settings.aSign) { /** remove currency sign */
  158. while (s.indexOf(settings.aSign) > -1) {
  159. s = s.replace(settings.aSign, '');
  160. }
  161. }
  162. s = s.replace(settings.skipFirstAutoStrip, '$1$2'); /** first replace anything before digits */
  163. s = s.replace(settings.skipLastAutoStrip, '$1'); /** then replace anything after digits */
  164. s = s.replace(settings.allowedAutoStrip, ''); /** then remove any uninterested characters */
  165. if (settings.altDec) {
  166. s = s.replace(settings.altDec, settings.aDec);
  167. } /** get only number string */
  168. var m = s.match(settings.numRegAutoStrip);
  169. s = m ? [m[1], m[2], m[3]].join('') : '';
  170. if ((settings.lZero === 'allow' || settings.lZero === 'keep') && strip_zero !== 'strip') {
  171. var parts = [],
  172. nSign = '';
  173. parts = s.split(settings.aDec);
  174. if (parts[0].indexOf('-') !== -1) {
  175. nSign = '-';
  176. parts[0] = parts[0].replace('-', '');
  177. }
  178. if (parts[0].length > settings.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
  179. parts[0] = parts[0].slice(1);
  180. }
  181. s = nSign + parts.join(settings.aDec);
  182. }
  183. if ((strip_zero && settings.lZero === 'deny') || (strip_zero && settings.lZero === 'allow' && settings.allowLeading === false)) {
  184. var strip_reg = '^' + settings.aNegRegAutoStrip + '0*(\\d' + (strip_zero === 'leading' ? ')' : '|$)');
  185. strip_reg = new RegExp(strip_reg);
  186. s = s.replace(strip_reg, '$1$2');
  187. }
  188. return s;
  189. }
  190. /**
  191. * places or removes brackets on negative values
  192. * works only when with pSign: 'p'
  193. */
  194. function negativeBracket(s, settings) {
  195. if (settings.pSign === 'p') {
  196. var brackets = settings.nBracket.split(',');
  197. if (!settings.hasFocus && !settings.removeBrackets) {
  198. s = s.replace(settings.aNeg, '');
  199. s = brackets[0] + s + brackets[1];
  200. } else if ((settings.hasFocus && s.charAt(0) === brackets[0]) || (settings.removeBrackets && s.charAt(0) === brackets[0])) {
  201. s = s.replace(brackets[0], settings.aNeg);
  202. s = s.replace(brackets[1], '');
  203. }
  204. }
  205. return s;
  206. }
  207. /**
  208. * function to handle numbers less than 0 that are stored in Exponential notation ex: .0000001 stored as 1e-7
  209. */
  210. function checkValue(value, settings) {
  211. if (value) {
  212. var checkSmall = +value;
  213. if (checkSmall < 0.000001 && checkSmall > -1) {
  214. value = +value;
  215. if (value < 0.000001 && value > 0) {
  216. value = (value + 10).toString();
  217. value = value.substring(1);
  218. }
  219. if (value < 0 && value > -1) {
  220. value = (value - 10).toString();
  221. value = '-' + value.substring(2);
  222. }
  223. value = value.toString();
  224. } else {
  225. var parts = value.split('.');
  226. if (parts[1] !== undefined) {
  227. if (+parts[1] === 0) {
  228. value = parts[0];
  229. } else {
  230. parts[1] = parts[1].replace(/0*$/, '');
  231. value = parts.join('.');
  232. }
  233. }
  234. }
  235. }
  236. return (settings.lZero === 'keep') ? value : value.replace(/^0*(\d)/, '$1');
  237. }
  238. /**
  239. * prepare number string to be converted to real number
  240. */
  241. function fixNumber(s, aDec, aNeg) {
  242. if (aDec && aDec !== '.') {
  243. s = s.replace(aDec, '.');
  244. }
  245. if (aNeg && aNeg !== '-') {
  246. s = s.replace(aNeg, '-');
  247. }
  248. if (!s.match(/\d/)) {
  249. s += '0';
  250. }
  251. return s;
  252. }
  253. /**
  254. * prepare real number to be converted to our format
  255. */
  256. function presentNumber(s, aDec, aNeg) {
  257. if (aNeg && aNeg !== '-') {
  258. s = s.replace('-', aNeg);
  259. }
  260. if (aDec && aDec !== '.') {
  261. s = s.replace('.', aDec);
  262. }
  263. return s;
  264. }
  265. /**
  266. * private function to check for empty value
  267. */
  268. function checkEmpty(iv, settings, signOnEmpty) {
  269. if (iv === '' || iv === settings.aNeg) {
  270. if (settings.wEmpty === 'zero') {
  271. return iv + '0';
  272. }
  273. if (settings.wEmpty === 'sign' || signOnEmpty) {
  274. return iv + settings.aSign;
  275. }
  276. return iv;
  277. }
  278. return null;
  279. }
  280. /**
  281. * private function that formats our number
  282. */
  283. function autoGroup(iv, settings) {
  284. iv = autoStrip(iv, settings);
  285. var testNeg = iv.replace(',', '.'),
  286. empty = checkEmpty(iv, settings, true);
  287. if (empty !== null) {
  288. return empty;
  289. }
  290. var digitalGroup = '';
  291. if (settings.dGroup === 2) {
  292. digitalGroup = /(\d)((\d)(\d{2}?)+)$/;
  293. } else if (settings.dGroup === 4) {
  294. digitalGroup = /(\d)((\d{4}?)+)$/;
  295. } else {
  296. digitalGroup = /(\d)((\d{3}?)+)$/;
  297. } /** splits the string at the decimal string */
  298. var ivSplit = iv.split(settings.aDec);
  299. if (settings.altDec && ivSplit.length === 1) {
  300. ivSplit = iv.split(settings.altDec);
  301. } /** assigns the whole number to the a variable (s) */
  302. var s = ivSplit[0];
  303. if (settings.aSep) {
  304. while (digitalGroup.test(s)) { /** re-inserts the thousand separator via a regular expression */
  305. s = s.replace(digitalGroup, '$1' + settings.aSep + '$2');
  306. }
  307. }
  308. if (settings.mDec !== 0 && ivSplit.length > 1) {
  309. if (ivSplit[1].length > settings.mDec) {
  310. ivSplit[1] = ivSplit[1].substring(0, settings.mDec);
  311. } /** joins the whole number with the decimal value */
  312. iv = s + settings.aDec + ivSplit[1];
  313. } else { /** if whole numbers only */
  314. iv = s;
  315. }
  316. if (settings.aSign) {
  317. var has_aNeg = iv.indexOf(settings.aNeg) !== -1;
  318. iv = iv.replace(settings.aNeg, '');
  319. iv = settings.pSign === 'p' ? settings.aSign + iv : iv + settings.aSign;
  320. if (has_aNeg) {
  321. iv = settings.aNeg + iv;
  322. }
  323. }
  324. if (testNeg < 0 && settings.nBracket !== null) { /** removes the negative sign and places brackets */
  325. iv = negativeBracket(iv, settings);
  326. }
  327. return iv;
  328. }
  329. /**
  330. * round number after setting by pasting or $().autoNumericSet()
  331. * private function for round the number
  332. * please note this handled as text - JavaScript math function can return inaccurate values
  333. * also this offers multiple rounding methods that are not easily accomplished in JavaScript
  334. */
  335. function autoRound(iv, settings) { /** value to string */
  336. iv = (iv === '') ? '0' : iv.toString();
  337. convertKeyToNumber(settings, 'mDec'); /** set mDec to number needed when mDec set by 'update method */
  338. if (settings.mRound === 'CHF') {
  339. iv = (Math.round(iv * 20) / 20).toString();
  340. }
  341. var ivRounded = '',
  342. i = 0,
  343. nSign = '',
  344. rDec = (typeof (settings.aPad) === 'boolean' || settings.aPad === null) ? (settings.aPad ? settings.mDec : 0) : +settings.aPad;
  345. var truncateZeros = function (ivRounded) { /** truncate not needed zeros */
  346. var regex = (rDec === 0) ? (/(\.(?:\d*[1-9])?)0*$/) : rDec === 1 ? (/(\.\d(?:\d*[1-9])?)0*$/) : new RegExp('(\\.\\d{' + rDec + '}(?:\\d*[1-9])?)0*$');
  347. ivRounded = ivRounded.replace(regex, '$1'); /** If there are no decimal places, we don't need a decimal point at the end */
  348. if (rDec === 0) {
  349. ivRounded = ivRounded.replace(/\.$/, '');
  350. }
  351. return ivRounded;
  352. };
  353. if (iv.charAt(0) === '-') { /** Checks if the iv (input Value)is a negative value */
  354. nSign = '-';
  355. iv = iv.replace('-', ''); /** removes the negative sign will be added back later if required */
  356. }
  357. if (!iv.match(/^\d/)) { /** append a zero if first character is not a digit (then it is likely to be a dot)*/
  358. iv = '0' + iv;
  359. }
  360. if (nSign === '-' && +iv === 0) { /** determines if the value is zero - if zero no negative sign */
  361. nSign = '';
  362. }
  363. if ((+iv > 0 && settings.lZero !== 'keep') || (iv.length > 0 && settings.lZero === 'allow')) { /** trims leading zero's if needed */
  364. iv = iv.replace(/^0*(\d)/, '$1');
  365. }
  366. var dPos = iv.lastIndexOf('.'),
  367. /** virtual decimal position */
  368. vdPos = (dPos === -1) ? iv.length - 1 : dPos,
  369. /** checks decimal places to determine if rounding is required */
  370. cDec = (iv.length - 1) - vdPos; /** check if no rounding is required */
  371. if (cDec <= settings.mDec) {
  372. ivRounded = iv; /** check if we need to pad with zeros */
  373. if (cDec < rDec) {
  374. if (dPos === -1) {
  375. ivRounded += '.';
  376. }
  377. var zeros = '000000';
  378. while (cDec < rDec) {
  379. zeros = zeros.substring(0, rDec - cDec);
  380. ivRounded += zeros;
  381. cDec += zeros.length;
  382. }
  383. } else if (cDec > rDec) {
  384. ivRounded = truncateZeros(ivRounded);
  385. } else if (cDec === 0 && rDec === 0) {
  386. ivRounded = ivRounded.replace(/\.$/, '');
  387. }
  388. if (settings.mRound !== 'CHF') {
  389. return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
  390. }
  391. if (settings.mRound === 'CHF') {
  392. dPos = ivRounded.lastIndexOf('.');
  393. iv = ivRounded;
  394. }
  395. } /** rounded length of the string after rounding */
  396. var rLength = dPos + settings.mDec,
  397. tRound = +iv.charAt(rLength + 1),
  398. ivArray = iv.substring(0, rLength + 1).split(''),
  399. odd = (iv.charAt(rLength) === '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2),
  400. onePass = true;
  401. if (odd !== 1) {
  402. odd = (odd === 0 && (iv.substring(rLength + 2, iv.length) > 0)) ? 1 : 0;
  403. }
  404. /*jslint white: true*/
  405. if ((tRound > 4 && settings.mRound === 'S') || /** Round half up symmetric */
  406. (tRound > 4 && settings.mRound === 'A' && nSign === '') || /** Round half up asymmetric positive values */
  407. (tRound > 5 && settings.mRound === 'A' && nSign === '-') || /** Round half up asymmetric negative values */
  408. (tRound > 5 && settings.mRound === 's') || /** Round half down symmetric */
  409. (tRound > 5 && settings.mRound === 'a' && nSign === '') || /** Round half down asymmetric positive values */
  410. (tRound > 4 && settings.mRound === 'a' && nSign === '-') || /** Round half down asymmetric negative values */
  411. (tRound > 5 && settings.mRound === 'B') || /** Round half even "Banker's Rounding" */
  412. (tRound === 5 && settings.mRound === 'B' && odd === 1) || /** Round half even "Banker's Rounding" */
  413. (tRound > 0 && settings.mRound === 'C' && nSign === '') || /** Round to ceiling toward positive infinite */
  414. (tRound > 0 && settings.mRound === 'F' && nSign === '-') || /** Round to floor toward negative infinite */
  415. (tRound > 0 && settings.mRound === 'U') || /** round up away from zero */
  416. (settings.mRound === 'CHF')) { /** Round Swiss FRanc */
  417. /*jslint white: false*/
  418. for (i = (ivArray.length - 1); i >= 0; i -= 1) { /** Round up the last digit if required, and continue until no more 9's are found */
  419. if (ivArray[i] !== '.') {
  420. if (settings.mRound === 'CHF' && ivArray[i] <= 2 && onePass) {
  421. ivArray[i] = 0;
  422. onePass = false;
  423. break;
  424. }
  425. if (settings.mRound === 'CHF' && ivArray[i] <= 7 && onePass) {
  426. ivArray[i] = 5;
  427. onePass = false;
  428. break;
  429. }
  430. if (settings.mRound === 'CHF' && onePass) {
  431. ivArray[i] = 10;
  432. onePass = false;
  433. } else {
  434. ivArray[i] = +ivArray[i] + 1;
  435. }
  436. if (ivArray[i] < 10) {
  437. break;
  438. }
  439. if (i > 0) {
  440. ivArray[i] = '0';
  441. }
  442. }
  443. }
  444. }
  445. ivArray = ivArray.slice(0, rLength + 1); /** Reconstruct the string, converting any 10's to 0's */
  446. ivRounded = truncateZeros(ivArray.join('')); /** return rounded value */
  447. return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
  448. }
  449. /**
  450. * truncate decimal part of a number
  451. */
  452. function truncateDecimal(s, settings, paste) {
  453. var aDec = settings.aDec,
  454. mDec = settings.mDec;
  455. s = (paste === 'paste') ? autoRound(s, settings) : s;
  456. if (aDec && mDec) {
  457. var parts = s.split(aDec);
  458. /** truncate decimal part to satisfying length
  459. * cause we would round it anyway */
  460. if (parts[1] && parts[1].length > mDec) {
  461. if (mDec > 0) {
  462. parts[1] = parts[1].substring(0, mDec);
  463. s = parts.join(aDec);
  464. } else {
  465. s = parts[0];
  466. }
  467. }
  468. }
  469. return s;
  470. }
  471. /**
  472. * checking that number satisfy format conditions
  473. * and lays between settings.vMin and settings.vMax
  474. * and the string length does not exceed the digits in settings.vMin and settings.vMax
  475. */
  476. function autoCheck(s, settings) {
  477. s = autoStrip(s, settings);
  478. s = truncateDecimal(s, settings);
  479. s = fixNumber(s, settings.aDec, settings.aNeg);
  480. var value = +s;
  481. return value >= settings.vMin && value <= settings.vMax;
  482. }
  483. /**
  484. * Holder object for field properties
  485. */
  486. function AutoNumericHolder(that, settings) {
  487. this.settings = settings;
  488. this.that = that;
  489. this.$that = $(that);
  490. this.formatted = false;
  491. this.settingsClone = autoCode(this.$that, this.settings);
  492. this.value = that.value;
  493. }
  494. AutoNumericHolder.prototype = {
  495. init: function (e) {
  496. this.value = this.that.value;
  497. this.settingsClone = autoCode(this.$that, this.settings);
  498. this.ctrlKey = e.ctrlKey;
  499. this.cmdKey = e.metaKey;
  500. this.shiftKey = e.shiftKey;
  501. this.selection = getElementSelection(this.that); /** keypress event overwrites meaningful value of e.keyCode */
  502. if (e.type === 'keydown' || e.type === 'keyup') {
  503. this.kdCode = e.keyCode;
  504. }
  505. this.which = e.which;
  506. this.processed = false;
  507. this.formatted = false;
  508. },
  509. setSelection: function (start, end, setReal) {
  510. start = Math.max(start, 0);
  511. end = Math.min(end, this.that.value.length);
  512. this.selection = {
  513. start: start,
  514. end: end,
  515. length: end - start
  516. };
  517. if (setReal === undefined || setReal) {
  518. setElementSelection(this.that, start, end);
  519. }
  520. },
  521. setPosition: function (pos, setReal) {
  522. this.setSelection(pos, pos, setReal);
  523. },
  524. getBeforeAfter: function () {
  525. var value = this.value,
  526. left = value.substring(0, this.selection.start),
  527. right = value.substring(this.selection.end, value.length);
  528. return [left, right];
  529. },
  530. getBeforeAfterStriped: function () {
  531. var parts = this.getBeforeAfter();
  532. parts[0] = autoStrip(parts[0], this.settingsClone);
  533. parts[1] = autoStrip(parts[1], this.settingsClone);
  534. return parts;
  535. },
  536. /**
  537. * strip parts from excess characters and leading zeroes
  538. */
  539. normalizeParts: function (left, right) {
  540. var settingsClone = this.settingsClone;
  541. right = autoStrip(right, settingsClone); /** if right is not empty and first character is not aDec, */
  542. /** we could strip all zeros, otherwise only leading */
  543. var strip = right.match(/^\d/) ? true : 'leading';
  544. left = autoStrip(left, settingsClone, strip); /** prevents multiple leading zeros from being entered */
  545. if ((left === '' || left === settingsClone.aNeg) && settingsClone.lZero === 'deny') {
  546. if (right > '') {
  547. right = right.replace(/^0*(\d)/, '$1');
  548. }
  549. }
  550. var new_value = left + right; /** insert zero if has leading dot */
  551. if (settingsClone.aDec) {
  552. var m = new_value.match(new RegExp('^' + settingsClone.aNegRegAutoStrip + '\\' + settingsClone.aDec));
  553. if (m) {
  554. left = left.replace(m[1], m[1] + '0');
  555. new_value = left + right;
  556. }
  557. } /** insert zero if number is empty and io.wEmpty == 'zero' */
  558. if (settingsClone.wEmpty === 'zero' && (new_value === settingsClone.aNeg || new_value === '')) {
  559. left += '0';
  560. }
  561. return [left, right];
  562. },
  563. /**
  564. * set part of number to value keeping position of cursor
  565. */
  566. setValueParts: function (left, right, paste) {
  567. var settingsClone = this.settingsClone,
  568. parts = this.normalizeParts(left, right),
  569. new_value = parts.join(''),
  570. position = parts[0].length;
  571. if (autoCheck(new_value, settingsClone)) {
  572. new_value = truncateDecimal(new_value, settingsClone, paste);
  573. if (position > new_value.length) {
  574. position = new_value.length;
  575. }
  576. this.value = new_value;
  577. this.setPosition(position, false);
  578. return true;
  579. }
  580. return false;
  581. },
  582. /**
  583. * helper function for expandSelectionOnSign
  584. * returns sign position of a formatted value
  585. */
  586. signPosition: function () {
  587. var settingsClone = this.settingsClone,
  588. aSign = settingsClone.aSign,
  589. that = this.that;
  590. if (aSign) {
  591. var aSignLen = aSign.length;
  592. if (settingsClone.pSign === 'p') {
  593. var hasNeg = settingsClone.aNeg && that.value && that.value.charAt(0) === settingsClone.aNeg;
  594. return hasNeg ? [1, aSignLen + 1] : [0, aSignLen];
  595. }
  596. var valueLen = that.value.length;
  597. return [valueLen - aSignLen, valueLen];
  598. }
  599. return [1000, -1];
  600. },
  601. /**
  602. * expands selection to cover whole sign
  603. * prevents partial deletion/copying/overwriting of a sign
  604. */
  605. expandSelectionOnSign: function (setReal) {
  606. var sign_position = this.signPosition(),
  607. selection = this.selection;
  608. if (selection.start < sign_position[1] && selection.end > sign_position[0]) { /** if selection catches something except sign and catches only space from sign */
  609. 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 */
  610. if (selection.start < sign_position[0]) {
  611. this.setSelection(selection.start, sign_position[0], setReal);
  612. } else {
  613. this.setSelection(sign_position[1], selection.end, setReal);
  614. }
  615. } else { /** else select with whole sign */
  616. this.setSelection(Math.min(selection.start, sign_position[0]), Math.max(selection.end, sign_position[1]), setReal);
  617. }
  618. }
  619. },
  620. /**
  621. * try to strip pasted value to digits
  622. */
  623. checkPaste: function () {
  624. if (this.valuePartsBeforePaste !== undefined) {
  625. var parts = this.getBeforeAfter(),
  626. oldParts = this.valuePartsBeforePaste;
  627. delete this.valuePartsBeforePaste; /** try to strip pasted value first */
  628. parts[0] = parts[0].substr(0, oldParts[0].length) + autoStrip(parts[0].substr(oldParts[0].length), this.settingsClone);
  629. if (!this.setValueParts(parts[0], parts[1], 'paste')) {
  630. this.value = oldParts.join('');
  631. this.setPosition(oldParts[0].length, false);
  632. }
  633. }
  634. },
  635. /**
  636. * process pasting, cursor moving and skipping of not interesting keys
  637. * if returns true, further processing is not performed
  638. */
  639. skipAllways: function (e) {
  640. var kdCode = this.kdCode,
  641. which = this.which,
  642. ctrlKey = this.ctrlKey,
  643. cmdKey = this.cmdKey,
  644. shiftKey = this.shiftKey; /** catch the ctrl up on ctrl-v */
  645. if (((ctrlKey || cmdKey) && e.type === 'keyup' && this.valuePartsBeforePaste !== undefined) || (shiftKey && kdCode === 45)) {
  646. this.checkPaste();
  647. return false;
  648. }
  649. /** codes are taken from http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
  650. * skip Fx keys, windows keys, other special keys
  651. * Thanks Ney Estrabelli for the FF for Mac meta key support "keycode 224"
  652. */
  653. if ((kdCode >= 112 && kdCode <= 123) || (kdCode >= 91 && kdCode <= 93) || (kdCode >= 9 && kdCode <= 31) || (kdCode < 8 && (which === 0 || which === kdCode)) || kdCode === 144 || kdCode === 145 || kdCode === 45 || kdCode === 224) {
  654. return true;
  655. }
  656. if ((ctrlKey || cmdKey) && kdCode === 65) { /** if select all (a=65)*/
  657. return true;
  658. }
  659. if ((ctrlKey || cmdKey) && (kdCode === 67 || kdCode === 86 || kdCode === 88)) { /** if copy (c=67) paste (v=86) or cut (x=88) */
  660. if (e.type === 'keydown') {
  661. this.expandSelectionOnSign();
  662. }
  663. if (kdCode === 86 || kdCode === 45) { /** try to prevent wrong paste */
  664. if (e.type === 'keydown' || e.type === 'keypress') {
  665. if (this.valuePartsBeforePaste === undefined) {
  666. this.valuePartsBeforePaste = this.getBeforeAfter();
  667. }
  668. } else {
  669. this.checkPaste();
  670. }
  671. }
  672. return e.type === 'keydown' || e.type === 'keypress' || kdCode === 67;
  673. }
  674. if (ctrlKey || cmdKey) {
  675. return true;
  676. }
  677. if (kdCode === 37 || kdCode === 39) { /** jump over thousand separator */
  678. var aSep = this.settingsClone.aSep,
  679. start = this.selection.start,
  680. value = this.that.value;
  681. if (e.type === 'keydown' && aSep && !this.shiftKey) {
  682. if (kdCode === 37 && value.charAt(start - 2) === aSep) {
  683. this.setPosition(start - 1);
  684. } else if (kdCode === 39 && value.charAt(start + 1) === aSep) {
  685. this.setPosition(start + 1);
  686. }
  687. }
  688. return true;
  689. }
  690. if (kdCode >= 34 && kdCode <= 40) {
  691. return true;
  692. }
  693. return false;
  694. },
  695. /**
  696. * process deletion of characters
  697. * returns true if processing performed
  698. */
  699. processAllways: function () {
  700. var parts; /** process backspace or delete */
  701. if (this.kdCode === 8 || this.kdCode === 46) {
  702. if (!this.selection.length) {
  703. parts = this.getBeforeAfterStriped();
  704. if (this.kdCode === 8) {
  705. parts[0] = parts[0].substring(0, parts[0].length - 1);
  706. } else {
  707. parts[1] = parts[1].substring(1, parts[1].length);
  708. }
  709. this.setValueParts(parts[0], parts[1]);
  710. } else {
  711. this.expandSelectionOnSign(false);
  712. parts = this.getBeforeAfterStriped();
  713. this.setValueParts(parts[0], parts[1]);
  714. }
  715. return true;
  716. }
  717. return false;
  718. },
  719. /**
  720. * process insertion of characters
  721. * returns true if processing performed
  722. */
  723. processKeypress: function () {
  724. var settingsClone = this.settingsClone,
  725. cCode = String.fromCharCode(this.which),
  726. parts = this.getBeforeAfterStriped(),
  727. left = parts[0],
  728. right = parts[1]; /** start rules when the decimal character key is pressed */
  729. /** always use numeric pad dot to insert decimal separator */
  730. if (cCode === settingsClone.aDec || (settingsClone.altDec && cCode === settingsClone.altDec) || ((cCode === '.' || cCode === ',') && this.kdCode === 110)) { /** do not allow decimal character if no decimal part allowed */
  731. if (!settingsClone.mDec || !settingsClone.aDec) {
  732. return true;
  733. } /** do not allow decimal character before aNeg character */
  734. if (settingsClone.aNeg && right.indexOf(settingsClone.aNeg) > -1) {
  735. return true;
  736. } /** do not allow decimal character if other decimal character present */
  737. if (left.indexOf(settingsClone.aDec) > -1) {
  738. return true;
  739. }
  740. if (right.indexOf(settingsClone.aDec) > 0) {
  741. return true;
  742. }
  743. if (right.indexOf(settingsClone.aDec) === 0) {
  744. right = right.substr(1);
  745. }
  746. this.setValueParts(left + settingsClone.aDec, right);
  747. return true;
  748. }
  749. /**
  750. * start rule on negative sign & prevent minus if not allowed
  751. */
  752. if (cCode === '-' || cCode === '+') {
  753. if (!settingsClone.aNeg) {
  754. return true;
  755. } /** caret is always after minus */
  756. if (left === '' && right.indexOf(settingsClone.aNeg) > -1) {
  757. left = settingsClone.aNeg;
  758. right = right.substring(1, right.length);
  759. } /** change sign of number, remove part if should */
  760. if (left.charAt(0) === settingsClone.aNeg) {
  761. left = left.substring(1, left.length);
  762. } else {
  763. left = (cCode === '-') ? settingsClone.aNeg + left : left;
  764. }
  765. this.setValueParts(left, right);
  766. return true;
  767. } /** digits */
  768. if (cCode >= '0' && cCode <= '9') { /** if try to insert digit before minus */
  769. if (settingsClone.aNeg && left === '' && right.indexOf(settingsClone.aNeg) > -1) {
  770. left = settingsClone.aNeg;
  771. right = right.substring(1, right.length);
  772. }
  773. if (settingsClone.vMax <= 0 && settingsClone.vMin < settingsClone.vMax && this.value.indexOf(settingsClone.aNeg) === -1 && cCode !== '0') {
  774. left = settingsClone.aNeg + left;
  775. }
  776. this.setValueParts(left + cCode, right);
  777. return true;
  778. } /** prevent any other character */
  779. return true;
  780. },
  781. /**
  782. * formatting of just processed value with keeping of cursor position
  783. */
  784. formatQuick: function () {
  785. var settingsClone = this.settingsClone,
  786. parts = this.getBeforeAfterStriped(),
  787. leftLength = this.value;
  788. if ((settingsClone.aSep === '' || (settingsClone.aSep !== '' && leftLength.indexOf(settingsClone.aSep) === -1)) && (settingsClone.aSign === '' || (settingsClone.aSign !== '' && leftLength.indexOf(settingsClone.aSign) === -1))) {
  789. var subParts = [],
  790. nSign = '';
  791. subParts = leftLength.split(settingsClone.aDec);
  792. if (subParts[0].indexOf('-') > -1) {
  793. nSign = '-';
  794. subParts[0] = subParts[0].replace('-', '');
  795. parts[0] = parts[0].replace('-', '');
  796. }
  797. if (subParts[0].length > settingsClone.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
  798. parts[0] = parts[0].slice(1);
  799. }
  800. parts[0] = nSign + parts[0];
  801. }
  802. var value = autoGroup(this.value, this.settingsClone),
  803. position = value.length;
  804. if (value) {
  805. /** prepare regexp which searches for cursor position from unformatted left part */
  806. var left_ar = parts[0].split(''),
  807. i = 0;
  808. for (i; i < left_ar.length; i += 1) { /** thanks Peter Kovari */
  809. if (!left_ar[i].match('\\d')) {
  810. left_ar[i] = '\\' + left_ar[i];
  811. }
  812. }
  813. var leftReg = new RegExp('^.*?' + left_ar.join('.*?'));
  814. /** search cursor position in formatted value */
  815. var newLeft = value.match(leftReg);
  816. if (newLeft) {
  817. position = newLeft[0].length;
  818. /** if we are just before sign which is in prefix position */
  819. if (((position === 0 && value.charAt(0) !== settingsClone.aNeg) || (position === 1 && value.charAt(0) === settingsClone.aNeg)) && settingsClone.aSign && settingsClone.pSign === 'p') {
  820. /** place caret after prefix sign */
  821. position = this.settingsClone.aSign.length + (value.charAt(0) === '-' ? 1 : 0);
  822. }
  823. } else if (settingsClone.aSign && settingsClone.pSign === 's') {
  824. /** if we could not find a place for cursor and have a sign as a suffix */
  825. /** place carret before suffix currency sign */
  826. position -= settingsClone.aSign.length;
  827. }
  828. }
  829. this.that.value = value;
  830. this.setPosition(position);
  831. this.formatted = true;
  832. }
  833. };
  834. /**
  835. * thanks to Anthony & Evan C
  836. */
  837. function autoGet(obj) {
  838. if (typeof obj === 'string') {
  839. obj = obj.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
  840. obj = '#' + obj.replace(/(:|\.)/g, '\\$1');
  841. /** obj = '#' + obj.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); */
  842. /** possible modification to replace the above 2 lines */
  843. }
  844. return $(obj);
  845. }
  846. /**
  847. * function to attach data to the element
  848. * and imitate the holder
  849. */
  850. function getHolder($that, settings, update) {
  851. var data = $that.data('autoNumeric');
  852. if (!data) {
  853. data = {};
  854. $that.data('autoNumeric', data);
  855. }
  856. var holder = data.holder;
  857. if ((holder === undefined && settings) || update) {
  858. holder = new AutoNumericHolder($that.get(0), settings);
  859. data.holder = holder;
  860. }
  861. return holder;
  862. }
  863. var methods = {
  864. /**
  865. * Method to initiate autoNumeric and attached the settings (default and options passed as a parameter
  866. * $(someSelector).autoNumeric('init'); // initiate autoNumeric with defaults
  867. * $(someSelector).autoNumeric('init', {option}); // initiate autoNumeric with options
  868. * $(someSelector).autoNumeric(); // initiate autoNumeric with defaults
  869. * $(someSelector).autoNumeric({option}); // initiate autoNumeric with options
  870. * options passes as a parameter example '{aSep: '.', aDec: ',', aSign: '€ '}
  871. */
  872. init: function (options) {
  873. return this.each(function () {
  874. var $this = $(this),
  875. settings = $this.data('autoNumeric'), /** attempt to grab 'autoNumeric' settings, if they don't exist returns "undefined". */
  876. tagData = $this.data(), /** attempt to grab HTML5 data, if they don't exist we'll get "undefined".*/
  877. $input = $this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])');
  878. if (typeof settings !== 'object') { /** If we couldn't grab settings, create them from defaults and passed options. */
  879. settings = $.extend({}, $.fn.autoNumeric.defaults, tagData, options, {
  880. aNum: '0123456789',
  881. hasFocus: false,
  882. removeBrackets: false,
  883. runOnce: false,
  884. 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']
  885. }); /** Merge defaults, tagData and options */
  886. if (settings.aDec === settings.aSep) {
  887. $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
  888. }
  889. $this.data('autoNumeric', settings); /** Save our new settings */
  890. } else {
  891. return this;
  892. }
  893. var holder = getHolder($this, settings);
  894. if (!$input && $this.prop('tagName').toLowerCase() === 'input') { /** checks for non-supported input types */
  895. $.error('The input type "' + $this.prop('type') + '" is not supported by autoNumeric()');
  896. }
  897. if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) === -1 && $this.prop('tagName').toLowerCase() !== 'input') {
  898. $.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
  899. }
  900. if (settings.runOnce === false && settings.aForm) { /** routine to format default value on page load */
  901. if ($input) {
  902. var setValue = true;
  903. if ($this[0].value === '' && settings.wEmpty === 'empty') {
  904. $this[0].value = '';
  905. setValue = false;
  906. }
  907. if ($this[0].value === '' && settings.wEmpty === 'sign') {
  908. $this[0].value = settings.aSign;
  909. setValue = false;
  910. }
  911. /** checks for page reload from back button
  912. * also checks for ASP.net form post back
  913. * the following HTML data attribute is REQUIRED (data-an-default="same value as the value attribute")
  914. * example: <asp:TextBox runat="server" id="someID" value="1234.56" data-an-default="1234.56">
  915. */
  916. if (setValue && $this.val() !== '' && ((settings.anDefault === null && $this[0].value === $this.prop('defaultValue')) || (settings.anDefault !== null && settings.anDefault.toString() === $this.val()))) {
  917. $this.autoNumeric('set', $this.val());
  918. }
  919. }
  920. if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1 && $this.text() !== '') {
  921. $this.autoNumeric('set', $this.text());
  922. }
  923. }
  924. settings.runOnce = true;
  925. if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
  926. $this.on('keydown.autoNumeric', function (e) {
  927. holder = getHolder($this);
  928. if (holder.settings.aDec === holder.settings.aSep) {
  929. $.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");
  930. }
  931. if (holder.that.readOnly) {
  932. holder.processed = true;
  933. return true;
  934. }
  935. /** The below streamed code / comment allows the "enter" keydown to throw a change() event */
  936. /** if (e.keyCode === 13 && holder.inVal !== $this.val()){
  937. $this.change();
  938. holder.inVal = $this.val();
  939. }*/
  940. holder.init(e);
  941. if (holder.skipAllways(e)) {
  942. holder.processed = true;
  943. return true;
  944. }
  945. if (holder.processAllways()) {
  946. holder.processed = true;
  947. holder.formatQuick();
  948. e.preventDefault();
  949. return false;
  950. }
  951. holder.formatted = false;
  952. return true;
  953. });
  954. $this.on('keypress.autoNumeric', function (e) {
  955. holder = getHolder($this);
  956. var processed = holder.processed;
  957. holder.init(e);
  958. if (holder.skipAllways(e)) {
  959. return true;
  960. }
  961. if (processed) {
  962. e.preventDefault();
  963. return false;
  964. }
  965. if (holder.processAllways() || holder.processKeypress()) {
  966. holder.formatQuick();
  967. e.preventDefault();
  968. return false;
  969. }
  970. holder.formatted = false;
  971. });
  972. $this.on('keyup.autoNumeric', function (e) {
  973. holder = getHolder($this);
  974. holder.init(e);
  975. var skip = holder.skipAllways(e);
  976. holder.kdCode = 0;
  977. delete holder.valuePartsBeforePaste;
  978. if ($this[0].value === holder.settings.aSign) { /** added to properly place the caret when only the currency is present */
  979. if (holder.settings.pSign === 's') {
  980. setElementSelection(this, 0, 0);
  981. } else {
  982. setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
  983. }
  984. }
  985. if (skip) {
  986. return true;
  987. }
  988. if (this.value === '') {
  989. return true;
  990. }
  991. if (!holder.formatted) {
  992. holder.formatQuick();
  993. }
  994. });
  995. $this.on('focusin.autoNumeric', function () {
  996. holder = getHolder($this);
  997. var $settings = holder.settingsClone;
  998. $settings.hasFocus = true;
  999. if ($settings.nBracket !== null) {
  1000. var checkVal = $this.val();
  1001. $this.val(negativeBracket(checkVal, $settings));
  1002. }
  1003. holder.inVal = $this.val();
  1004. var onEmpty = checkEmpty(holder.inVal, $settings, true);
  1005. if (onEmpty !== null && onEmpty !== '') {
  1006. $this.val(onEmpty);
  1007. }
  1008. });
  1009. $this.on('focusout.autoNumeric', function () {
  1010. holder = getHolder($this);
  1011. var $settings = holder.settingsClone,
  1012. value = $this.val(),
  1013. origValue = value;
  1014. $settings.hasFocus = false;
  1015. var strip_zero = ''; /** added to control leading zero */
  1016. if ($settings.lZero === 'allow') { /** added to control leading zero */
  1017. $settings.allowLeading = false;
  1018. strip_zero = 'leading';
  1019. }
  1020. if (value !== '') {
  1021. value = autoStrip(value, $settings, strip_zero);
  1022. if (checkEmpty(value, $settings) === null && autoCheck(value, $settings, $this[0])) {
  1023. value = fixNumber(value, $settings.aDec, $settings.aNeg);
  1024. value = autoRound(value, $settings);
  1025. value = presentNumber(value, $settings.aDec, $settings.aNeg);
  1026. } else {
  1027. value = '';
  1028. }
  1029. }
  1030. var groupedValue = checkEmpty(value, $settings, false);
  1031. if (groupedValue === null) {
  1032. groupedValue = autoGroup(value, $settings);
  1033. }
  1034. if (groupedValue !== holder.inVal || groupedValue !== origValue) {
  1035. $this.val(groupedValue);
  1036. $this.change();
  1037. delete holder.inVal;
  1038. }
  1039. });
  1040. }
  1041. });
  1042. },
  1043. /**
  1044. * method to remove settings and stop autoNumeric() - does not remove the formatting
  1045. * $(someSelector).autoNumeric('destroy'); // destroy autoNumeric
  1046. * no parameters accepted
  1047. */
  1048. destroy: function () {
  1049. return $(this).each(function () {
  1050. var $this = $(this);
  1051. $this.off('.autoNumeric');
  1052. $this.removeData('autoNumeric');
  1053. });
  1054. },
  1055. /**
  1056. * method to update settings - can be call as many times
  1057. * $(someSelector).autoNumeric('update', {options}); // updates the settings
  1058. * options passes as a parameter example '{aSep: '.', aDec: ',', aSign: '€ '}
  1059. */
  1060. update: function (options) {
  1061. return $(this).each(function () {
  1062. var $this = autoGet($(this)),
  1063. settings = $this.data('autoNumeric');
  1064. if (typeof settings !== 'object') {
  1065. $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'update' method");
  1066. }
  1067. var strip = $this.autoNumeric('get');
  1068. settings = $.extend(settings, options);
  1069. getHolder($this, settings, true);
  1070. if (settings.aDec === settings.aSep) {
  1071. $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
  1072. }
  1073. $this.data('autoNumeric', settings);
  1074. if ($this.val() !== '' || $this.text() !== '') {
  1075. return $this.autoNumeric('set', strip);
  1076. }
  1077. return;
  1078. });
  1079. },
  1080. /**
  1081. * method to format value sent as a parameter ""
  1082. * $(someSelector).autoNumeric('set', 'value'}); // formats the value being passed
  1083. * value passed as a string - can be a integer '1234' or double '1234.56789'
  1084. * must contain only numbers and one decimal (period) character
  1085. */
  1086. set: function (valueIn) {
  1087. if (valueIn === null) {
  1088. return;
  1089. }
  1090. return $(this).each(function () {
  1091. var $this = autoGet($(this)),
  1092. settings = $this.data('autoNumeric'),
  1093. value = valueIn.toString(),
  1094. testValue = valueIn.toString(),
  1095. $input = $this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])');
  1096. if (typeof settings !== 'object') {
  1097. $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'set' method");
  1098. }
  1099. /** allows locale decimal separator to be a comma */
  1100. if ((testValue === $this.attr('value') || testValue === $this.text()) && settings.runOnce === false) {
  1101. value = value.replace(',', '.');
  1102. }
  1103. if (!$.isNumeric(+value)) {
  1104. $.error("The value (" + value + ") being 'set' is not numeric and has caused a error to be thrown");
  1105. }
  1106. value = checkValue(value, settings);
  1107. settings.setEvent = true;
  1108. value.toString();
  1109. if (value !== '') {
  1110. value = autoRound(value, settings);
  1111. }
  1112. value = presentNumber(value, settings.aDec, settings.aNeg);
  1113. if (!autoCheck(value, settings)) {
  1114. value = autoRound('', settings);
  1115. }
  1116. value = autoGroup(value, settings);
  1117. if ($input) {
  1118. return $this.val(value);
  1119. }
  1120. if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1) {
  1121. return $this.text(value);
  1122. }
  1123. return false;
  1124. });
  1125. },
  1126. /**
  1127. * method to get the unformatted that accepts up to one parameter
  1128. * $(someSelector).autoNumeric('get'); no parameters accepted
  1129. * values returned as ISO numeric string "1234.56" where the decimal character is a period
  1130. * only the first element in the selector is returned
  1131. */
  1132. get: function () {
  1133. var $this = autoGet($(this)),
  1134. settings = $this.data('autoNumeric');
  1135. if (typeof settings !== 'object') {
  1136. $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'get' method");
  1137. }
  1138. var getValue = '';
  1139. /** determine the element type then use .eq(0) selector to grab the value of the first element in selector */
  1140. if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
  1141. getValue = $this.eq(0).val();
  1142. } else if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1) {
  1143. getValue = $this.eq(0).text();
  1144. } else {
  1145. $.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
  1146. }
  1147. if ((getValue === '' && settings.wEmpty === 'empty') || (getValue === settings.aSign && (settings.wEmpty === 'sign' || settings.wEmpty === 'empty'))) {
  1148. return '';
  1149. }
  1150. if (getValue !== '' && settings.nBracket !== null) {
  1151. settings.removeBrackets = true;
  1152. getValue = negativeBracket(getValue, settings);
  1153. settings.removeBrackets = false;
  1154. }
  1155. if (settings.runOnce || settings.aForm === false) {
  1156. getValue = autoStrip(getValue, settings);
  1157. }
  1158. getValue = fixNumber(getValue, settings.aDec, settings.aNeg);
  1159. if (+getValue === 0 && settings.lZero !== 'keep') {
  1160. getValue = '0';
  1161. }
  1162. if (settings.lZero === 'keep') {
  1163. return getValue;
  1164. }
  1165. getValue = checkValue(getValue, settings);
  1166. return getValue; /** returned Numeric String */
  1167. },
  1168. /**
  1169. * The 'getString' method used jQuerys .serialize() method that creates a text string in standard URL-encoded notation
  1170. * it then loops through the string and un-formats the inputs with autoNumeric
  1171. * $(someSelector).autoNumeric('getString'); no parameter accepted
  1172. * values returned as ISO numeric string "1234.56" where the decimal character is a period
  1173. */
  1174. getString: function () {
  1175. var isAutoNumeric = false,
  1176. $this = autoGet($(this)),
  1177. formFields = $this.serialize(),
  1178. formParts = formFields.split('&'),
  1179. formIndex = $('form').index($this),
  1180. allFormElements = $('form:eq(' + formIndex + ')'),
  1181. aiIndex = [], /* all input index */
  1182. scIndex = [], /* successful control index */
  1183. rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, /* from jQuery serialize method */
  1184. rsubmittable = /^(?:input|select|textarea|keygen)/i, /* from jQuery serialize method */
  1185. rcheckableType = /^(?:checkbox|radio)$/i,
  1186. rnonAutoNumericTypes = /^(?:button|checkbox|color|date|datetime|datetime-local|email|file|image|month|number|password|radio|range|reset|search|submit|time|url|week)/i,
  1187. count = 0;
  1188. /*jslint unparam: true*/
  1189. /* index of successful elements */
  1190. $.each(allFormElements[0], function (i, field) {
  1191. if (field.name !== '' && rsubmittable.test(field.localName) && !rsubmitterTypes.test(field.type) && !field.disabled && (field.checked || !rcheckableType.test(field.type))) {
  1192. scIndex.push(count);
  1193. count = count + 1;
  1194. } else {
  1195. scIndex.push(-1);
  1196. }
  1197. });
  1198. /* index of all inputs tags except checkbox */
  1199. count = 0;
  1200. $.each(allFormElements[0], function (i, field) {
  1201. if (field.localName === 'input' && (field.type === '' || field.type === 'text' || field.type === 'hidden' || field.type === 'tel')) {
  1202. aiIndex.push(count);
  1203. count = count + 1;
  1204. } else {
  1205. aiIndex.push(-1);
  1206. if (field.localName === 'input' && rnonAutoNumericTypes.test(field.type)) {
  1207. count = count + 1;
  1208. }
  1209. }
  1210. });
  1211. $.each(formParts, function (i, miniParts) {
  1212. miniParts = formParts[i].split('=');
  1213. var scElement = $.inArray(i, scIndex);
  1214. if (scElement > -1 && aiIndex[scElement] > -1) {
  1215. var testInput = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')'),
  1216. settings = testInput.data('autoNumeric');
  1217. if (typeof settings === 'object') {
  1218. if (miniParts[1] !== null) {
  1219. miniParts[1] = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')').autoNumeric('get').toString();
  1220. formParts[i] = miniParts.join('=');
  1221. isAutoNumeric = true;
  1222. }
  1223. }
  1224. }
  1225. });
  1226. /*jslint unparam: false*/
  1227. if (!isAutoNumeric) {
  1228. $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'getString' method");
  1229. }
  1230. return formParts.join('&');
  1231. },
  1232. /**
  1233. * The 'getString' method used jQuerys .serializeArray() method that creates array or objects that can be encoded as a JSON string
  1234. * it then loops through the string and un-formats the inputs with autoNumeric
  1235. * $(someSelector).autoNumeric('getArray'); no parameter accepted
  1236. * values returned as ISO numeric string "1234.56" where the decimal character is a period
  1237. */
  1238. getArray: function () {
  1239. var isAutoNumeric = false,
  1240. $this = autoGet($(this)),
  1241. formFields = $this.serializeArray(),
  1242. formIndex = $('form').index($this),
  1243. allFormElements = $('form:eq(' + formIndex + ')'),
  1244. aiIndex = [], /* all input index */
  1245. scIndex = [], /* successful control index */
  1246. rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, /* from jQuery serialize method */
  1247. rsubmittable = /^(?:input|select|textarea|keygen)/i, /* from jQuery serialize method */
  1248. rcheckableType = /^(?:checkbox|radio)$/i,
  1249. rnonAutoNumericTypes = /^(?:button|checkbox|color|date|datetime|datetime-local|email|file|image|month|number|password|radio|range|reset|search|submit|time|url|week)/i,
  1250. count = 0;
  1251. /*jslint unparam: true*/
  1252. /* index of successful elements */
  1253. $.each(allFormElements[0], function (i, field) {
  1254. if (field.name !== '' && rsubmittable.test(field.localName) && !rsubmitterTypes.test(field.type) && !field.disabled && (field.checked || !rcheckableType.test(field.type))) {
  1255. scIndex.push(count);
  1256. count = count + 1;
  1257. } else {
  1258. scIndex.push(-1);
  1259. }
  1260. });
  1261. /* index of all inputs tags */
  1262. count = 0;
  1263. $.each(allFormElements[0], function (i, field) {
  1264. if (field.localName === 'input' && (field.type === '' || field.type === 'text' || field.type === 'hidden' || field.type === 'tel')) {
  1265. aiIndex.push(count);
  1266. count = count + 1;
  1267. } else {
  1268. aiIndex.push(-1);
  1269. if (field.localName === 'input' && rnonAutoNumericTypes.test(field.type)) {
  1270. count = count + 1;
  1271. }
  1272. }
  1273. });
  1274. $.each(formFields, function (i, field) {
  1275. var scElement = $.inArray(i, scIndex);
  1276. if (scElement > -1 && aiIndex[scElement] > -1) {
  1277. var testInput = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')'),
  1278. settings = testInput.data('autoNumeric');
  1279. if (typeof settings === 'object') {
  1280. field.value = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')').autoNumeric('get').toString();
  1281. isAutoNumeric = true;
  1282. }
  1283. }
  1284. });
  1285. /*jslint unparam: false*/
  1286. if (!isAutoNumeric) {
  1287. $.error("None of the successful form inputs are initialized by autoNumeric.");
  1288. }
  1289. return formFields;
  1290. },
  1291. /**
  1292. * The 'getSteetings returns the object with autoNumeric settings for those who need to look under the hood
  1293. * $(someSelector).autoNumeric('getSettings'); // no parameters accepted
  1294. * $(someSelector).autoNumeric('getSettings').aDec; // return the aDec setting as a string - ant valid setting can be used
  1295. */
  1296. getSettings: function () {
  1297. var $this = autoGet($(this));
  1298. return $this.eq(0).data('autoNumeric');
  1299. }
  1300. };
  1301. /**
  1302. * autoNumeric function
  1303. */
  1304. $.fn.autoNumeric = function (method) {
  1305. if (methods[method]) {
  1306. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  1307. }
  1308. if (typeof method === 'object' || !method) {
  1309. return methods.init.apply(this, arguments);
  1310. }
  1311. $.error('Method "' + method + '" is not supported by autoNumeric()');
  1312. };
  1313. /**
  1314. * Defaults are public - these can be overridden by the following:
  1315. * HTML5 data attributes
  1316. * Options passed by the 'init' or 'update' methods
  1317. * Use jQuery's $.extend method - great way to pass ASP.NET current culture settings
  1318. */
  1319. $.fn.autoNumeric.defaults = {
  1320. /** allowed thousand separator characters
  1321. * comma = ','
  1322. * period "full stop" = '.'
  1323. * apostrophe is escaped = '\''
  1324. * space = ' '
  1325. * none = ''
  1326. * NOTE: do not use numeric characters
  1327. */
  1328. aSep: ',',
  1329. /** digital grouping for the thousand separator used in Format
  1330. * dGroup: '2', results in 99,99,99,999 common in India for values less than 1 billion and greater than -1 billion
  1331. * dGroup: '3', results in 999,999,999 default
  1332. * dGroup: '4', results in 9999,9999,9999 used in some Asian countries
  1333. */
  1334. dGroup: '3',
  1335. /** allowed decimal separator characters
  1336. * period "full stop" = '.'
  1337. * comma = ','
  1338. */
  1339. aDec: '.',
  1340. /** allow to declare alternative decimal separator which is automatically replaced by aDec
  1341. * developed for countries the use a comma ',' as the decimal character
  1342. * and have keyboards\numeric pads that have a period 'full stop' as the decimal characters (Spain is an example)
  1343. */
  1344. altDec: null,
  1345. /** allowed currency symbol
  1346. * Must be in quotes aSign: '$', a space is allowed aSign: '$ '
  1347. */
  1348. aSign: '',
  1349. /** placement of currency sign
  1350. * for prefix pSign: 'p',
  1351. * for suffix pSign: 's',
  1352. */
  1353. pSign: 'p',
  1354. /** maximum possible value
  1355. * value must be enclosed in quotes and use the period for the decimal point
  1356. * value must be larger than vMin
  1357. */
  1358. vMax: '9999999999999.99',
  1359. /** minimum possible value
  1360. * value must be enclosed in quotes and use the period for the decimal point
  1361. * value must be smaller than vMax
  1362. */
  1363. vMin: '-9999999999999.99',
  1364. /** max number of decimal places = used to override decimal places set by the vMin & vMax values
  1365. * value must be enclosed in quotes example mDec: '3',
  1366. * This can also set the value via a call back function mDec: 'css:#
  1367. */
  1368. mDec: null,
  1369. /** method used for rounding
  1370. * mRound: 'S', Round-Half-Up Symmetric (default)
  1371. * mRound: 'A', Round-Half-Up Asymmetric
  1372. * mRound: 's', Round-Half-Down Symmetric (lower case s)
  1373. * mRound: 'a', Round-Half-Down Asymmetric (lower case a)
  1374. * mRound: 'B', Round-Half-Even "Bankers Rounding"
  1375. * mRound: 'U', Round Up "Round-Away-From-Zero"
  1376. * mRound: 'D', Round Down "Round-Toward-Zero" - same as truncate
  1377. * mRound: 'C', Round to Ceiling "Toward Positive Infinity"
  1378. * mRound: 'F', Round to Floor "Toward Negative Infinity"
  1379. */
  1380. mRound: 'S',
  1381. /** controls decimal padding
  1382. * aPad: true - always Pad decimals with zeros
  1383. * aPad: false - does not pad with zeros.
  1384. * aPad: `some number` - pad decimals with zero to number different from mDec
  1385. * thanks to Jonas Johansson for the suggestion
  1386. */
  1387. aPad: true,
  1388. /** places brackets on negative value -$ 999.99 to (999.99)
  1389. * visible only when the field does NOT have focus the left and right symbols should be enclosed in quotes and seperated by a comma
  1390. * nBracket: null, nBracket: '(,)', nBracket: '[,]', nBracket: '<,>' or nBracket: '{,}'
  1391. */
  1392. nBracket: null,
  1393. /** Displayed on empty string
  1394. * wEmpty: 'empty', - input can be blank
  1395. * wEmpty: 'zero', - displays zero
  1396. * wEmpty: 'sign', - displays the currency sign
  1397. */
  1398. wEmpty: 'empty',
  1399. /** controls leading zero behavior
  1400. * lZero: 'allow', - allows leading zeros to be entered. Zeros will be truncated when entering additional digits. On focusout zeros will be deleted.
  1401. * lZero: 'deny', - allows only one leading zero on values less than one
  1402. * lZero: 'keep', - allows leading zeros to be entered. on fousout zeros will be retained.
  1403. */
  1404. lZero: 'allow',
  1405. /** determine if the select all keyboard command will select
  1406. * the complete input text or only the input numeric value
  1407. * if the currency symbol is between the numeric value and the negative sign only the numeric value will sellected
  1408. */
  1409. sNumber: true,
  1410. /** determine if the default value will be formatted on page ready.
  1411. * true = automatically formats the default value on page ready
  1412. * false = will not format the default value
  1413. */
  1414. aForm: true,
  1415. /** helper option for ASP.NET postback
  1416. * should be the value of the unformatted default value
  1417. * examples:
  1418. * no default value='' {anDefault: ''}
  1419. * value=1234.56 {anDefault: '1234.56'}
  1420. */
  1421. anDefault: null
  1422. };
  1423. }(jQuery));