Jump to content

Make text field ignore SPACE key?


galvin

Recommended Posts

Anyone know how to use javascript to make it so that if a "SPACE" is the 1st character typed in a text field, it will be ignored?

 

I saw this site where there was a text field and if you hit SPACE 1st by accident (or intentionally), the cursor moved forward for a split second, but jumped right back to the beginning again.  In other words, it wasn't letting the user type a SPACE as the 1st character.

 

I know I could look into just stripping any accidential leading spaces on the server side, but I'd like to use this cool feature I saw on that website if possible (unfortunately, I forget the name of the website).

Link to comment
Share on other sites

document.getElementById('textfieldId').addEventListener( 'keydown', function( e ) { 
  if( e.keyCode == 32 && document.getElementById( 'textfieldId' ).selectionStart == 0 && document.getElementById( 'textfieldId' ).selectionEnd == 0 ) {
    e.preventDefault();
  }
}, false );

I think.. for firefox anyhow, IE adds event listeners differently from the rest. (Google is your friend)

And iirc selectionstart and end are firefox specific.

 

Your best bet? A javascript framework like jquery and using the preventDefault() on the event ;)

Link to comment
Share on other sites

And on that note, the javascript isn't even really necessary. Just run trim() (if you are using php) on the serverside to deal with this. Unless the input is used on the client side without being sent to the server.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.