Skip to content

Instantly share code, notes, and snippets.

@carlosrberto
Last active August 15, 2016 19:40
Show Gist options
  • Save carlosrberto/6482be67149ca74a347f to your computer and use it in GitHub Desktop.
Save carlosrberto/6482be67149ca74a347f to your computer and use it in GitHub Desktop.
jQuery onlynumber

jQuery onlynumber

$('input').onlynumber();
/*
* jQuery onlynumber
*
* Copyright (c) 2013 Carlos Roberto Gomes Junior
* http://carlosroberto.name/
*
* Licensed under a Creative Commons Attribution 3.0 License
* http://creativecommons.org/licenses/by-sa/3.0/
*
* Version: 0.1
*/
(function( $ ){
function OnlyNumber (el) {
this.el = el;
this.oldValue = this.el.val();
this.pasteTimer = null;
this.el.on('keyup.onlynumber', $.proxy(this.handler, this));
this.el.on('paste.onlynumber', $.proxy(this.pasteHandler, this));
}
OnlyNumber.prototype = {
pasteHandler() {
clearTimeout(this.pasteTimer);
this.pasteTimer = setTimeout(() => {
this.handler();
}, 100);
},
handler: function( event ) {
var val = this.el.val();
if ( val === "" ) {
this.oldValue = val;
return;
}
if ( !val.match(/^ ?[0-9 ]+$/) ) {
this.el.val( this.oldValue );
} else {
this.oldValue = this.el.val();
}
},
destroy: function() {
this.el.off('.onlynumber');
$.removeData(this.el, 'onlynumber');
}
};
$.fn.onlynumber = function() {
return this.each(function(){
$.data(this, 'onlynumber', new OnlyNumber( $(this) ));
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment