jquery (or pure js) simulate enter key pressed for testing

morgancodes picture morgancodes · Jul 18, 2010 · Viewed 132.6k times · Source

What the best way to simulate the user pressing "enter"? $(element).keypress() doesn't seem to allow me to pass in the actual key that was pressed.

This is for unit testing.

Answer

redsquare picture redsquare · Jul 18, 2010

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);