Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a key to an input text field using Javascript?

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?

like image 621
Arian Avatar asked Aug 15 '11 06:08

Arian


People also ask

How do you get input value directly in JavaScript?

We can get the value of the text input field using various methods in JavaScript. There is a text value property that can set and return the value of the value attribute of a text field. Also, we can use the jquery val() method inside the script to get or set the value of the text input field.

How do you trigger button click on Enter key press using JavaScript?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.


2 Answers

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

like image 78
Ghostoy Avatar answered Oct 05 '22 22:10

Ghostoy


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

or change to jQuery :)

like image 28
ryamx Avatar answered Oct 05 '22 22:10

ryamx