Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 338
morgancodes Avatar asked Jul 18 '10 18:07

morgancodes


People also ask

How do you check if Enter key is pressed in jQuery?

To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox'). keypress(function(event){ var keycode = (event. keyCode ?

How do you check if Enter key is pressed in JavaScript?

And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.

Is it possible to simulate pressing [Enter] key on input text?

javascript - Simulate pressing [enter] key on input text - Stack Overflow My code worked perfectly on changed the value of input automatic on page load with a delay between it. But there's another problem, When I tried to simulate pressing the [enter] key on the input,...

How to simulate keypress events with JavaScript?

To simulate keypress events with JavaScript, we can use the dispatch method with an event object. We can use the KeyboardEvent constructor to create a keyboard event with various options.

How to check if pressed key is enter in JavaScript?

If you want to check if pressed key is enter: var input = document.querySelector("._7uiwk._qy55y"); input.addEventListener('keypress', function(ev){ if(ev.keyCode === 13 || ev.which === 13){ // enter was pressed } }); If you want to prevent submitting the form on enter/submit:


1 Answers

Demo Here

var e = jQuery.Event("keypress"); e.which = 13; //choose the one you want e.keyCode = 13; $("#theInputToTest").trigger(e); 
like image 77
redsquare Avatar answered Sep 28 '22 03:09

redsquare