Skip to content

Instantly share code, notes, and snippets.

@ruslanchek
Created November 7, 2014 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruslanchek/259252d41d768cee818b to your computer and use it in GitHub Desktop.
Save ruslanchek/259252d41d768cee818b to your computer and use it in GitHub Desktop.
Price formatter
(function ($) {
$.fn.KVNum = function (method) {
var settings = {
};
function process($input){
var input = $($input)[0];
var value = $input.val(),
start = input.selectionStart,
end = input.selectionEnd,
spaces = 0;
value = value + '';
value = value.replace(/[^0-9,.]/g, "");
var l1 = value.length;
value = value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
var l2 = value.length;
spaces = l2 - l1 - $input.data('spaces');
$input.data('spaces', $input.data('spaces') + spaces);
if(parseInt(value) > 0){
value = parseInt(value.replace(/[^0-9]/g, "")).toString();
value = value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
$input.val(value);
if(spaces >= 0){
$input[0].setSelectionRange(start + spaces, end + spaces);
}
}
var methods = {
apply: function(){
return this.each(function () {
process($(this));
});
},
init: function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('KVNum');
if (!data) {
$this.data('KVNum', {
settings: $.extend(settings, options)
});
$(this).data('spaces', 0);
$this.off('keyup.KVNum').on('keyup.KVNum', function(e){
var KEYS = [37, 38, 39, 40, 13, 9, 16];
if(!in_array(e.keyCode, KEYS)) {
process($this);
}
});
$this.off('blur.KVNumClear').on('blur.KVNumClear', function(){
var value = $(this).val();
if(parseInt(value) <= 0){
value = '0';
}
$(this).val(value);
$(this).data('spaces', 0);
});
}
});
}
};
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('KVNum Invalid method!');
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment