galvin Posted July 2, 2009 Share Posted July 2, 2009 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). Quote Link to comment Share on other sites More sharing options...
gevans Posted July 2, 2009 Share Posted July 2, 2009 Very easy. Write a function that checks the value of the field. If the character is a space remove it. The input field, and an onkeypress event that triggers the function. Quote Link to comment Share on other sites More sharing options...
Axeia Posted July 2, 2009 Share Posted July 2, 2009 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 Quote Link to comment Share on other sites More sharing options...
Adam Posted July 2, 2009 Share Posted July 2, 2009 Don't rely on this to trim your inputs though if it's important they are, JS can be turned off remember. Quote Link to comment Share on other sites More sharing options...
haku Posted July 5, 2009 Share Posted July 5, 2009 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.