forked from price-format/Jquery-Price-Format
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprototype.priceformat.min.js
1 lines (1 loc) · 2.61 KB
/
prototype.priceformat.min.js
1
NumberFormat=Class.create({initialize:function(t,e){this.el=$(t);var e=Object.extend({prefix:"US$ ",centsSeparator:".",thousandsSeparator:",",limit:!1,centsLimit:2,clearPrefix:!1,allowNegative:!1,clearOnEmpty:!1},e);this.is_number=/[0-9]/,this.prefix=e.prefix,this.centsSeparator=e.centsSeparator,this.thousandsSeparator=e.thousandsSeparator,this.limit=e.limit,this.centsLimit=e.centsLimit,this.clearPrefix=e.clearPrefix,this.allowNegative=e.allowNegative,this.clearOnEmpty=e.clearOnEmpty,this.clearPrefix&&(Event.observe(this.el,"blur",this.clearPrefix.bind(this)),Event.observe(this.el,"focus",this.addPrefix.bind(this))),Event.observe(this.el,"keyup",this.priceIt.bind(this)),Event.observe(this.el,"keydown",this.keyCheck.bind(this)),window.ctrl_down=!1,Event.observe(window,"keyup",function(t){return window.ctrl_down=t.ctrlKey,!0}),Event.observe(window,"keydown",function(t){return window.ctrl_down=t.ctrlKey,!0}),this.el.value.length>0&&(this.priceIt(),this.clearPrefix())},keyCheck:function(t){var e=t.keyCode?t.keyCode:t.which,i=String.fromCharCode(e),r=!1,s=t.target.value,a=this.priceFormat(s+i);(e>=48&&e<=57||e>=96&&e<=105)&&(r=!0),8==e&&(r=!0),9==e&&(r=!0),13==e&&(r=!0),17==e&&(r=!0),46==e&&(r=!0),35==e&&(r=!0),36==e&&(r=!0),37==e&&(r=!0),39==e&&(r=!0),!this.allowNegative||189!=e&&109!=e||(r=!0),window.ctrl_down&&(86==e&&(r=!0),67==e&&(r=!0),88==e&&(r=!0),82==e&&(r=!0),84==e&&(r=!0),76==e&&(r=!0),87==e&&(r=!0),81==e&&(r=!0),78==e&&(r=!0),65==e&&(r=!0)),r||(t.preventDefault(),t.stopPropagation(),s!=a&&(t.target.value=a))},toNumbers:function(t){for(var e="",i=0;i<t.length;i++)char=t.charAt(i),0==e.length&&0==char&&(char=!1),char&&char.match(this.is_number)&&(this.limit?e.length<this.limit&&(e+=char):e+=char);return e},priceFormat:function(t,e){if(!e&&(""===t||t==this.priceFormat("0",!0))&&clearOnEmpty)return"";var i=this.fillWithZeroes(this.toNumbers(t)),r="",s=0,a=i.substr(i.length-this.centsLimit,this.centsLimit),n=i.substr(0,i.length-this.centsLimit);if(i=n+this.centsSeparator+a,this.thousandsSeparator){for(var h=n.length;h>0;h--)char=n.substr(h-1,1),s++,s%3==0&&(char=this.thousandsSeparator+char),r=char+r;r.substr(0,1)==this.thousandsSeparator&&(r=r.substring(1,r.length)),i=r+this.centsSeparator+a}return!this.allowNegative||t.indexOf("-")==-1||0==n&&0==a||(i="-"+i),this.prefix&&(i=this.prefix+i),i},fillWithZeroes:function(t){for(;t.length<this.centsLimit+1;)t="0"+t;return t},priceIt:function(){var t=this.el.value,e=this.priceFormat(t);t!=e&&(this.el.value=e)},addPrefix:function(){var t=el.value;el.value=this.prefix+t},clearPrefix:function(){if(""!=prefix.trim()&&this.clearPrefix){var t=el.value.split(this.prefix);el.value=t[1]}}});