jQuery code to allow numbers and arrow keys in textbox

I have already posted about "jQuery code to allow only numbers in textbox", but one of my reader asked me to allow arrow keys as well. I have modified the code slightly to allow arrow keys. I thought it's good idea to share with all my readers. See below jQuery code.

$(document).ready(function(){ 
$("#txtNumbers").keydown(function(event) {
   if(event.shiftKey)
        event.preventDefault();
   if (event.keyCode == 46 || event.keyCode == 8) {
   }
   else {
        if (event.keyCode < 95) {
          
          if (event.keyCode < 48 || event.keyCode > 57) {
              if (event.keyCode >= 37 && event.keyCode <= 40) {  
               }
              else
              {
                event.preventDefault();
              }
          }
        } 
        else {
              if (event.keyCode < 96 || event.keyCode > 105) {
                  event.preventDefault();
              }
        }
      }
   });
});
See live Demo and Code.

Also read my related posts, which describe how to allow alphabets, numbers 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...