I have an input field, where the user can write things. I want that, if the user press the key "1", to simulate another key press "F". So, if the user typer the character 1, in the field it will display 1f. How can i do it, without using jQuery?
Asked
Active
Viewed 3.2k times
7
-
4Are you just trying to append the `f` character to the text box, or do you need to actually make it seem like the `f` key was pressed? – Joe Enos Jun 26 '13 at 14:44
-
1no, i must do it to looks like the f key was pressed. – Mateus Viccari Jun 26 '13 at 16:51
1 Answers
5
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent ("keypress", true, true, window,
0, 0, 0, 0,
13, 13);
var canceled = !body.dispatchEvent(evt);
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.initKeyEvent
For Webkit-based browser the initialization might be a bit different
initKeyboardEvent(in DOMString typeArg,
in boolean canBubbleArg,
in boolean cancelableArg,
in views::AbstractView viewArg,
in DOMString keyIdentifierArg,
in unsigned long keyLocationArg,
in boolean ctrlKeyArg,
in boolean shiftKeyArg,
in boolean altKeyArg,
in boolean metaKeyArg,
in boolean altGraphKeyArg);

Carlos Bergen
- 813
- 2
- 8
- 20
-
-
3`initKeyEvent` has been deprecated and probably will stop working soon. See [this answer](http://stackoverflow.com/a/19883789/1269037) in the duplicated question. – Dan Dascalescu Sep 02 '15 at 06:11