模拟< enter>在javascript中按键触发表单提交 [英] Simulate <enter> keypress in javascript to trigger a form-submit
问题描述
我发现了十几篇关于如何做到这一点的SO文章,但没有一篇正在发挥作用。
我正在尝试编写一些测试,并且我想测试当我在输入
中按输入时,表单确实会回发。但是,我不能让它来模拟这个。
无论我选择哪种方法, keypress
事件正在被触发 - 事件监听器看到它 - 但表单没有被提交。
输入我们必须使用 KeyboardEvent构造函数并将事件传递给输入的 dispatchEvent 方法。
const event = new KeyboardEvent(keypress,{view:window,keyCode:13,bubbles:true,cancelable:true}); document.querySelector (input)。dispatchEvent(event);
< ; - - 在提交时返回错误,但这很好......我们只看到我们是否可以提交提交 - >< form action =POST> < input id =myinputtype ='text'value =foo/>< / form>< div id =output>< / div>
您可以在关于触发和创建活动的mdn文档
I've found a dozen different SO articles on how to do this, but none of them are working.
I'm trying to write some tests, and I want to test that when I press enter in an input
, the form does indeed post back. However, I can't get it to simulate this.
No matter which method I choose, the keypress
event is being triggered--event listeners see it--but the form isn't being submitted.
Html
<!-- returns an error on submit, but that's 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 keypress like this?
If you focus on the text box (in jsFiddle) and physically press enter, the page will post back and will return something like:
This is what I'm trying to achieve, only in code.
Here's why:
$("input").on("keypress", function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
I ran into this in my code base, and I want to test that this sort of thing doesn't happen again.
To simulate the keypress event on the input we have to use the KeyboardEvent constructor and pass the event to the input's dispatchEvent method.
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's 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 more information on mdn documentation on triggering and creating events
这篇关于模拟< enter>在javascript中按键触发表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!