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?
If you need keyup events too, it is also possible to simulate keyup events by changing "keydown" to "keyup" in the code snippet. This also sends the event to the entire webpage, hence the document . If you want only a specific element to receive the event, you can substitute document for the desired element.
// Add event listener on keyup document. addEventListener('keyup', (event) => { var name = event. key; var code = event. code; // Alert the key name and key code on keydown alert(`Key pressed ${name} \r\n Key code value: ${code}`); }, false);
If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor. An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …}
You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With