jQuery code to allow only numbers in textbox

Below jQuery code snippets will allow only numbers in the textbox. However backspace and delete keys are also allowed.

$(document).ready(function(){ 
   $("#<%= txtNumbers.ClientID%>").keydown(function(e) 
   {
       if (e.shiftKey) 
           e.preventDefault();
       else 
       {
           var nKeyCode = e.keyCode;
           //Ignore Backspace and Tab keys
           if (nKeyCode == 8 || nKeyCode == 9)
               return;
           if (nKeyCode < 95) 
           {
               if (nKeyCode < 48 || nKeyCode > 57)
                   e.preventDefault();
           }
           else 
           {
               if (nKeyCode < 96 || nKeyCode > 105) 
               e.preventDefault();
           }
       }
   });
});
See live Demo and Code

Also read my related posts, which describe how to allow arrow keys with number, alphabets and specific characters.

Feel free to contact me for any help related to jQuery. I will gladly help you.



Responsive Menu
Add more content here...