jquery (or pure js) simulate enter key pressed for testing
What the best way to simulate the user pressing "enter"? $(element).keypress()开发者_JS百科 doesn't seem to allow me to pass in the actual key that was pressed.
This is for unit testing.
Demo Here
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);
For those who want to do this in pure javascript, look at:
Using standard KeyboardEvent
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
- initKeyboardEvent for IE9+, Chrome and Safari
- initKeyEvent for Firefox
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
精彩评论