Skip to content

Instantly share code, notes, and snippets.

@pielgrzym
Forked from sukima/jquery.input_formatter.js
Created June 27, 2011 18:54
Show Gist options
  • Save pielgrzym/1049507 to your computer and use it in GitHub Desktop.
Save pielgrzym/1049507 to your computer and use it in GitHub Desktop.
Different scope approach
(function($){
$.fn.extend({
formatInput: function(custom_settings) {
var settings = $.extend({
regex:".*",
format_number: true,
max_length: false,
errback: undefined
}, custom_settings);
return this.each(function() {
var elem = $(this);
if(settings.format_number == true)
{
elem.bind("keyup.format_number", formatEvent);
}
elem.bind("keypress.filter_input", filterEvent);
});
function filterEvent(e) {
var s = settings;
var regex = new RegExp(s.regex);
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
var string = String.fromCharCode(key);
var elem = $(this);
if (key == 8 || key == 9 || key == 13 || key == 35 || key == 36|| key == 37 || key == 39 || key == 46) {
if ($.browser.mozilla) {
if (event.charCode == 0 && event.keyCode == key) {
return true;
}
}
}
if(s.max_length != false)
{
var value = elem.val();
if(value != undefined && value.length >= s.max_length)
{
if(s.errback != undefined)
{
s.errback(elem, reason="max_length");
}
return false;
}
}
if(regex.test(string))
{
return true;
} else {
if(s.errback != undefined)
{
s.errback(elem, reason="regex");
}
return false;
}
};
function formatEvent(e) {
var elem = $(this);
var initial_value = elem.val().replace(" ", "");
elem.val(insertSpaces(initial_value));
};
function insertSpaces(number) {
return number.replace(/(\d)(?=(?:\d{3})+$)/g, "$1 ");
};
},
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment