Allow Only Numbers in TextBox jQuery



Some of the user information, you want in number/numeric form only and you can force a textbox to accept only numeric input. Using jQuery we can control user input with different key event handlers. So in this post I am going to share the jQuery code snippet to allow only numbers in textbox.

Lets take a simple example for understand this:


Enter Numbers : <input type="text" name="number" id="number" />

If you want to allow only numbers in textbox of your form, you can use following jQuery code snippet.


$(document).ready(function () {
  //called when key is down
  $("#number").bind("keydown", function (event) {
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 

	    // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
              // let it happen, don't do anything
              return;
        } else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault();
            }
        }
   });
});

Above code will allow only numeric input and disable cut, copy and paste in the textbox. If you want to enable copy and paste you can add following code:


jQuery(".number").bind("keydown", function (event) {
			
	if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
		 // Allow: Ctrl+A
		(event.keyCode == 65 && event.ctrlKey === true) || 
		
		// Allow: Ctrl+C
		(event.keyCode == 67 && event.ctrlKey === true) || 
		
		// Allow: Ctrl+V
		(event.keyCode == 86 && event.ctrlKey === true) || 
		
		// Allow: home, end, left, right
		(event.keyCode >= 35 && event.keyCode <= 39)) {
		  // let it happen, don't do anything
		  return;
	} else {
		// Ensure that it is a number and stop the keypress
		if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
			event.preventDefault(); 
		}   
	}
});

If you want to disable copy, cut and paste from any text field you can use following code :


// to disable cut, copy and paste
   $('input[type=text]').bind("cut copy paste",function(e) {
          e.preventDefault();
   });

Explanation: This jQuery code snippet allow the user’s to input only numbers and disable the other characters. When the use press the the key our handler will check the keyCode and if it is not of number it will prevent the character.

This allows select all(CTRL+A) and arrow keys inside textbox.  You can also disable the cut, copy and paste in the textbox so only the numbers you will get at server side.

Hope this tutorial will work for you to allow only numbers in textbox using jQuery.

Live Demo