Simulate a <enter> click in javascript to run a submit form

I found dozens of SO articles on how to do this, but none of them work.

I am trying to write some tests, and I want to verify that when I press enter in input , the form is indeed sent back. However, I cannot get him to imitate this.

No matter which method I choose, the keypress event is keypress - event listeners see it, but the form is not submitted.

jsFiddle link :

Html

 <!-- returns an error on submit, but that fine... we're only seeing if we can get a submit to happen --> <form action="POST"> <input id="myinput" type='text' value="foo" /> </form> <div id="output"></div> 

Javascript

 $(function () { var $input = $("#myinput"); $input.on("keypress", function (evt) { $("#output").append("Typed: " + evt.keyCode + ", but the form didn't submit.<br>"); }); $("form").on("submit", function () { alert("The form submitted!"); } ); // try jQuery event var e = $.Event("keypress", { keyCode: 13 }); $input.trigger(e); // try vanilla javascript var input = $input[0]; e = new Event("keypress"); e.keyCode = 13; e.target = input; input.dispatchEvent(e); e = document.createEvent("HTMLEvents"); e.initEvent("keypress", true, true); e.keyCode = 13; e.target = input; input.dispatchEvent(e); }); 

Is it possible to simulate an actual keystroke as follows?

If you focus on the text field (in jsFiddle) and physically press enter , the page will return a message and return something like:

enter image description here

This is what I'm trying to achieve, only in code.

That's why:

 $("input").on("keypress", function (e) { if (e.keyCode == 13) { e.preventDefault(); } }); 

I came across this in my code base, and I want to check that this kind of thing will not happen again.

+5
source share
1 answer

To simulate a keypress event on a tab, we must use the KeyboardEvent Constructor and pass the event to the dispatchEvent input.

 const event = new KeyboardEvent("keypress", { view: window, keyCode: 13, bubbles: true, cancelable: true }); document.querySelector("input").dispatchEvent(event); 
 <!-- returns an error on submit, but that fine... we're only seeing if we can get a submit to happen --> <form action="POST"> <input id="myinput" type='text' value="foo" /> </form> <div id="output"></div> 

You can see additional information about the mdn documentation when starting and creating events.

0
source

Source: https://habr.com/ru/post/1216143/


All Articles