[英]How does one trigger an enter key event on a text input field in the presence of a button in the same form?
When one attaches an onkeyup
event callback to an <input type=text">
element, the event is triggered when the enter key is pressed and the text input element is focussed. 当将
onkeyup
事件回调附加到<input type=text">
元素时,将在按下Enter键并聚焦文本输入元素时触发该事件。
When one attaches an onkeyup
event callback to an <input type=text">
element, the event is not triggered when the enter key is pressed and the text input element is foccussed if an <input type="submit">
element exists in the same form. 当一个附加一个
onkeyup
事件回调至<input type=text">
元素,当输入键被按下,并且如果文本输入元件foccussed 不会触发事件<input type="submit">
元素中存在相同的形式。
<form method="post">
<input type="text" required>
<input id="eggs" type="text">
<input type="submit">
</form>
<script>
box = document.getElementById("eggs");
box.onkeyup = function(key) {
console.log(key);
};
</script>
Actual: 实际:
The following happens when there is no <input type="submit">
element in the same form: 当没有相同格式的
<input type="submit">
元素时,将发生以下情况:
https://i.imgur.com/IxV1Lqf.png https://i.imgur.com/IxV1Lqf.png
The following happens where there is a <input type="submit">
element in the same form: 如果存在具有相同格式的
<input type="submit">
元素,则会发生以下情况:
https://i.imgur.com/pDf4pSI.png https://i.imgur.com/pDf4pSI.png
Expected: 预期:
An event should be fired when the enter key is pressed, regardless of whether there is a button in the form. 按下Enter键时,无论表单中是否存在按钮,都应触发一个事件。
Here's my solution: 这是我的解决方案:
1. prevent a keydown on the form from submitting the form (you could check for the right key to make a Shift+Enter still submit the form fe) 1.防止表单上的按键提交表单(您可以检查右键以使Shift + Enter仍然提交表单fe)
2. set an event handler on the submit button to actually submit the form. 2.在“提交”按钮上设置一个事件处理程序,以实际提交表单。
<html>
<head></head>
<body>
<h3>Enter key event will not fire:</h3>
<form method="post" id="form">
<input type="text" required>
<input id="eggs" type="text">
<input type="submit" id="submit">
</form>
<script>
eggsbox = document.getElementById("eggs");
eggsbox.onkeyup = function(key) {
console.log(key);
};
form = document.getElementById("form");
form.onkeydown = function(e) {
if(e.keyCode==13) { // only prevent on Enter (otherwide you can't type anything...)
e.preventDefault();
}
}
submitButton = document.getElementById("submit");
submitButton.onClick = function(e) {
form = document.getElementById("form");
form.submit(); // this will also trigger the validation!
}
</script>
</body>
</html>
here's the fiddle: https://jsfiddle.net/wcskdL1o/ 这是小提琴: https : //jsfiddle.net/wcskdL1o/
document.getElementById('eggs').onkeydown = function(x){
if(x.keyCode == 13){
// submit or try using <button>...</button> instead of <a>
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.