How to allow only numbers being entered in a text field? The best way is to catch event when new value is entered and filtered it with regular expression.

There are couple of ways how the value can make into the text field. It can be typed by user or pasted by user (with the right button of mouse). I have created a universal solution that will run in both of those cases:

$("#textfield").bind("keyup paste", function(){
	setTimeout(jQuery.proxy(function() {
		this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);		

Dima Svirid

Software architect, JAVA, Spring, Hibernate, AngularJs, Backbone, MongoDB, Oracle. CTO and Co-Founder of

More Posts

Follow Me: