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
https://forums.phpfreaks.com/topic/164540-make-text-field-ignore-space-key/
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 ;)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.