WRITTEN BY

ntechi

VN:F [1.9.22_1171]
Rating: 5.0/5 (5 votes cast)

Demo

JQuery Allow Only Numbers

Browser Support

For a frontend developer when it is asked to do something unique that person will think of JQuery first. Today a simple jquery code to allow only numbers to a text-box. Below code will allow following key events :

  • Backspace
  • Delete
  • Tab
  • Escape
  • Enter
  • Ctrl+A
  • Home
  • end
  • left
  • right

Just add a class to textbox .onlyNumbers and paste the following jquery code :


$(document).ready(function() {

    $(".onlyNumbers").keydown(function(event) {

        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) {
            return;
        }
        else {

            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                event.preventDefault();
            }
        }
    });

});

You can also apply this to textarea.

Demo:



JQuery Allow Only Numbers, 5.0 out of 5 based on 5 ratings

Demo

  • http://twitter.com/Rockstox Hunter Davis

    Really great feature!!!!!! Great work!

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
  • vikas

    Really great
    Can you pls help me with provision to accept decimal also

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
  • Andre Figueiredo

    not working for drag’n’drop =/

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
  • Rikin Patel

    nice… but what about decimal value….?

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
  • Louis

    Absolutely not working fine on a azerty french keyboard where you have to press shift + nb if you want to type a number. Using keycodes is a major issue regarding the different types of keyboards.

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)