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?

4
  • Your question is hard to understand. Can you try to clarify what you want to do, please? Commented Aug 15, 2011 at 6:56
  • Its easy to understand the question, here is an answer: stackoverflow.com/questions/2903991/… Commented Aug 15, 2011 at 7: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") Commented Aug 15, 2011 at 7:13
  • Why don't you want to say txt.value = "a" (or txt.value = txt.value + "a")? Commented Aug 15, 2011 at 7:25

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

or change to jQuery :)

Comments

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);

1 Comment

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!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.