8

How I can send a combination of keys (like Ctrl+C or Alt+Shift) when cursor goes in a input text field using Javascript?

I'm not using jQuery but am using MS-Ajax. Is it possible using 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 called it I got an error:

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

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

Error: DOM Exception: NOT_SUPPORTED_ERR (9)

where is my fault?

Arian
  • 12,793
  • 66
  • 176
  • 300
  • Your question is hard to understand. Can you try to clarify what you want to do, please? – Paul Aug 15 '11 at 06:56
  • Its easy to understand the question, here is an answer: http://stackoverflow.com/questions/2903991/how-to-detect-ctrlv-ctrlc-using-javascript – NimChimpsky Aug 15 '11 at 07:02
  • I want to Send keys to a textbox using Javascript not jQUERY.for example How I can send "A" key to text box (I don't write this txt.text="a") – Arian Aug 15 '11 at 07:13
  • Why don't you want to say `txt.value = "a"` (or `txt.value = txt.value + "a"`)? – nnnnnn Aug 15 '11 at 07:25

4 Answers4

2

Simulate key events is not easy. See this question: Simulating user input for TDD JavaScript. You'd better try other workarounds.

Community
  • 1
  • 1
Ghostoy
  • 2,689
  • 19
  • 18
1

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

or change to jQuery :)

foebe
  • 359
  • 7
  • 17
ryamx
  • 11
  • 1
  • 2
0

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

bresleveloper
  • 5,940
  • 3
  • 33
  • 47
0

You cannot trigger key events as if a user has actually pressed the key. See here for a relevant question. You can trigger events for your own bindings, like so (JSFiddle here, copied from answer shown above):

 var e = jQuery.Event("keydown");
 e.which = 50; // # Some key code value
 $("input").trigger(e);
Community
  • 1
  • 1
hayesgm
  • 8,678
  • 1
  • 38
  • 40
  • 2
    Hahaha, okay, and you don't want my advice on the topic either, then. Am I forcing you to use jQuery by using it as an example? That's not the relevant issue. Have fun figuring this out! – hayesgm Aug 15 '11 at 07:35