1

We're hoping to detect a keypress and the key from a user typing outside of a form field. And append that key to the form field and focus the user back into the form field. Essentially, hijacking any and all key events, and using placing them in a form field.

Any help would be greatly appreciated. We're happy using jquery for this type of client-side JS. We've gotten as far as detecting the keypress events, but focusing and appending that key to a particular field on the page is a bit beyond us.

Ryan Teuscher
  • 133
  • 1
  • 1
  • 5

1 Answers1

0

Listen for keydown on window.

var input = $("input");
$(window).keydown(function(e) {
    input.focus(); // focus the input
    input.val( input.val() + String.fromCharCode(e.which));
    return false;
});

You may need to tune this code up, but you'll get the idea.

esamatti
  • 18,293
  • 11
  • 75
  • 82
  • You need to `e.stopPropagation();` and `return false;` to prevent double-typing. – Jared Farrish May 31 '11 at 01:56
  • Thanks for the note. Return false is enough in jQuery. http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false/1357151#1357151 – esamatti May 31 '11 at 02:07
  • What about modifiers? Key presses that don't generate a visible character? And the sheer annoyance factor? – RobG May 31 '11 at 02:16
  • Unfortunately, this is clearing out the value field when a key is typed for the first time on a new page. On the second instance of leaving the input and typing a key it doesn't clear the text. Any ideas? – Ryan Teuscher May 31 '11 at 02:47