Jul 18, 2012

JQuery Allow Only Numbers

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 :



[js]
$(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();
}
}
});

});
[/js]



You can also apply this to textarea.

Demo:





5 comments :

  1. Really great feature!!!!!! Great work!

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

    ReplyDelete
  3. Andre Figueiredo27/10/12 6:30 AM

    not working for drag'n'drop =/

    ReplyDelete
  4. Rikin Patel4/11/12 12:28 AM

    nice... but what about decimal value....?

    ReplyDelete
  5. 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.

    ReplyDelete