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. Ajax/Javascript, HTML5, Android, iPhone/iPad, JAVA, PHP, Cold Fusion, SQL, Air, Flash, Open source software, Frameworks

More Posts

Follow Me:

 

5 Responses to Allow only numbers (numeric) in a field with jQuery

  1. Anonymous says:

    Great solution

  2. Tiram Makuza says:

    Greeting from Tiram.

    My name is Tiram I am single woman, looking for.
    honest and caring friend for a serious relationships,
    and I came across and became interesting in you,
    and I will like you to reply.
    with Email address (tiram_makuza@yahoo.co.uk).
    so that I can send you my photos and give you some.
    details about my self, waiting to read from you,

    Yours New Friend TIRAM.

  3. Carol Chamis says:

    Thanks! it works.

  4. Carol Chamis says:

    Thanks! it works.

  5. $('#textfield').keyup(function () {.
    if (this.value!= this.value.replace(/[^0-9.]/g, '')) {.
    this.value = this.value.replace(/[^0-9.]/g, '');.
    }.

    });
    This would let you use the arrow keys and delete/ backspace key as well.

Leave a Reply