views:

6419

answers:

2

I've read all the answers on to this questions and none of the solutions seem to work.

Also, I am getting the vibe that triggering keypress with special characters does not work at all. Can someone verify who has done this?

edit: the solution does not work. Try it in firebug on stackoverflow:

e = jQuery.Event("keydown");
e.which = 67;
$("#wmd-input").trigger(e)

wmd-input in the question input. 65 is A, so 67 must be an alpha key. No alpha key is entered into the question box.

+16  A: 

This code is working for me. It is triggered by special keys like arrows and ctrl

$("input").keydown(function (e) {
    alert(e.which)
});

You may want to use e.keyCode instead of e.which if you are using IE

EDIT

If you want to trigger the keypress or keydown event then all you have to do is:

e = jQuery.Event("keydown")
e.which = 50 # Some key value
$("input").trigger(e)
Nadia Alramli
the question is how to trigger, not how to capture
Chad Grant
I have set up a demo of your code here - http://jsbin.com/elolu
Russ Cam
I added an example for triggering the event
Nadia Alramli
Very nice answer. Worth noting that jQuery.Event is available for jQuery 1.3 or greater. It became relevant in this question: http://stackoverflow.com/questions/1823617/how-do-i-have-jquerys-autocomplete-plugin-display-its-dropdown-list-upon-page-lo/1823732
artlung
+1  A: 

If you're using jQuery UI too, you can do like this:

var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);
OreiA