Your code works ok, except for the following case: If the user moves the caret by using the arrow keys, and then types space, the hyphen is added to the end of the field instead of being inserted at the caret position.
–
Sorin PostelnicuOct 26 '12 at 10:34

2 Answers
2

The problem is that return 109 doesn't do what you want it to do. In an event handler, you return true or false depending on whether or not you want the browser to execute the default action. In keydown, you would return false to prevent the character from being inserted.

Try it out here, what this does is allow the space to be added, but then instantly does a replace of spaces for hyphens by passing a function to .val(). For older versions of jQuery, it'd look like this:

What's the advantage of keyup over keydown? Daniel's code works nicely (at least in Chrome), even if you keep the space depressed, and it isn't as visually jarring as suddenly have spaces replaced with dashes (esp. after the space is depressed for a long period of time).
–
Peter AjtaiOct 4 '10 at 21:28

Thank you for the code.. but I do prefer Daniels code because the space character is never even executed... thus the split second it takes for the replace function to complete is avoided and the cursor doesn't jump around.
–
quakkelsOct 4 '10 at 21:30

1

@quakkels - You can copy/paste, why is it everyone forgets this when designing validation?
–
Nick Craver♦Oct 4 '10 at 21:39

1

@quakkels - I think your priorities as a UI designer are a bit backwards but whatever works. I wouldn't ever expect a user to lay on the spacebar for entering a URL, and if they did it would be very, very rare and it'd still work, but if you prefer a lot more code to reach the same goal, so be it. Functionality, then appearances, always. My problem is more of an accepted answer not accounting for the very common copy/paste case being accepted and the next person using it blindly, it makes this question/answer a very bad resource.
–
Nick Craver♦Oct 4 '10 at 21:45