How to send key to input text field using javascript?

How can I send a keyboard shortcut (e.g. Ctrl + C or Alt + Shift) when the cursor goes to the text input field using Javascript?

I do not use jQuery , but I use MS-Ajax. Is it possible to use MS-Ajax DOM?

EDIT 1)

According to @Ghostoy help, I wrote this code:

function simulateKeyPress() { var evt = document.createEvent("KeyboardEvent"); evt.initKeyEvent("keypress", true, true, window, 0, 0, 0, 0, 0, "e".charCodeAt(0)) var canceled = !body.dispatchEvent(evt); if (canceled) { alert("canceled"); } else { alert("not canceled"); } } 

but when he called, he got an error:

 Error: Object doesn't support property or method 'initKeyEvent' 

and then I changed KeyboardEvent to KeyEvents . I got this error:

 Error: DOM Exception: NOT_SUPPORTED_ERR (9) 

Where is my mistake?

+4
javascript html ajax
source share
4 answers

Imitating key events is not easy. See This Question: Simulating User Input for JavaScript TDD . You better try other workarounds.

+1
source share

Change evt.initKeyEvent(...) to evt.initKeyboardEvent(...)

or change to jQuery :)

+1
source share

You cannot trigger key events as if the user had pressed a key. See here for the relevant question. You can fire events for your own bindings , for example (JSFiddle here , copied from the answer above):

  var e = jQuery.Event("keydown"); e.which = 50; // # Some key code value $("input").trigger(e); 
0
source share

have annwer! we only need to extend the JQ Event with all its necessary attributes, see here: http://bresleveloper.blogspot.co.il/2013/03/jsjq-simulate-enter-event.html

0
source share

All Articles