Thursday, June 16, 2011

How to Disable Spacebar in text box using jQuery

For one of my requirement, I need to restrict/disable end-user to enter space in the input field or textbox. This was piece of cake with jQuery. All I need to do is to check the keycode of spacebar and restrict its default action on keydown event. See below jQuery code. "txtNoSpaces" is the name of the textbox.
$(document).ready(function(){ 
  $("#txtNoSpaces").keydown(function(event) {
     if (event.keyCode == 32) {
         event.preventDefault();
     }
  });
});
See live Demo and Code.
Also read,
jQuery code to allow only numbers in textbox
jQuery code to allow numbers and arrow keys in textbox
Restrict Shift Key using jQuery

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