[英]Hitting enter instead of clicking submit is not working in JavaScript
I am trying to allow my user to hit enter in the input field which should trigger the same click event as if they had clicked on the "submit" button with their mouse.我试图让我的用户在输入字段中按回车键,这应该触发相同的点击事件,就好像他们用鼠标点击了“提交”按钮一样。
document.getElementById("input").addEventListener("keyup", function() {
if (KeyboardEvent.code == "13") {
document.getElementById("button").click();
}
});
However the keycode doesn't work.但是键码不起作用。 The content of the function works when I do KeyboardEvent.code.= "13" but I don't know how to make it listen to only the enter key.
function 的内容在我执行 KeyboardEvent.code.= "13" 时有效,但我不知道如何让它只听回车键。
I have tried looking t other questions on Stackoverflow (notably here ), but my code editor is saying those notations are deprecated.我曾尝试在 Stackoverflow 上查看其他问题(尤其是此处),但我的代码编辑器说这些符号已被弃用。
I think that the issue is in a misunderstanding of KeyboardEvent.code
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code meaning.我认为问题在于对
KeyboardEvent.code
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code含义的误解。 In your case, it will always equal undefined.在您的情况下,它将始终等于未定义。 Instead, you need to get the code from the event.
相反,您需要从事件中获取代码。 See the example below
请参阅下面的示例
document.getElementById("input").addEventListener("keyup", function (e) {
if (e.code === "Enter") {
document.getElementById("button").click();
}
});
To handle this behavior in a form you only need to have a form with a submit button:要在表单中处理此行为,您只需要一个带有提交按钮的表单:
<form onSubmit="someSubmitFn()" method="post">
<!-- form elements -->
<button type="submit">Submit</button>
</form>
You can also try with e.keyCode
instead of KeyboardEvent.code
:您也可以尝试使用
e.keyCode
而不是KeyboardEvent.code
:
document.getElementById("input").addEventListener("keyup", function(e) {
if (e.keyCode == "13") {
document.getElementById("button").click();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.