html text input field disable space character

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
me666
Forum Commoner
Posts: 87
Joined: Wed Oct 08, 2008 5:04 pm

html text input field disable space character

Post by me666 »

Hi all, i have a login page using email and password combinations. What i want is that if u press the space bar or paste a space into the text field it is deleted/disallowed. I think this is possible using javascript but ive not used much javascript in the past. Any ideas would be great.
thanks guys :D
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: html text input field disable space character

Post by kaszu »

Code: Select all

<input type="text" name="name" id="inp" value="" />

Code: Select all

document.getElementById('inp').onkeydown = function (event) {
  var event = event || window.event;  // get event object
  var key = event.keyCode || event.which; // get key cross-browser
  
  if (key == 32) { //Space bar key code
    //Prevent default action, which is inserting space
    if (event.preventDefault) event.preventDefault(); //normal browsers
    event.returnValue = false; //IE
  }
};
Test: http://jsbin.com/iduxu3/edit
me666
Forum Commoner
Posts: 87
Joined: Wed Oct 08, 2008 5:04 pm

Re: html text input field disable space character

Post by me666 »

thanks mate, works a treat :D
Post Reply