gpt4 book ai didi

javascript - 在输入文本字段上按 Enter 键提交表单

转载 作者:行者123 更新时间:2023-11-28 18:46:32 24 4
gpt4 key购买 nike

在我的代码中,我希望能够按 Enter 键并按我的输入按钮。目前我运气不好,对我的代码有什么建议吗?谢谢,

<form>

<input type="text" id="input" placeholder="Enter your name">

<input type="button" id="button" value="enter">

</form>

<h1 id="output">Please Complete Form</h1>


<script>
var button = document.getElementById("button");
var input;
var output;

button.addEventListener("click", clickHandler, false);
input.addEventListener("keypress", handle, false);

function clickHandler () {

input = document.getElementById("input");
output = document.getElementById("output");

output.innerHTML = input.value;

}

function handle(e){
if(e.keyCode==13){
document.getElementById('button').click();
}

}

</script>

最佳答案

You do not need to attach keypress event over input as it is a nature of input type text to submit the form when enter key is pressed.

注意:变量input在附加addEventListener时未定义,因此会产生错误。

试试这个:

var button = document.getElementById("button");
var input = document.getElementById("input");
button.addEventListener("click", clickHandler, false);

function clickHandler() {
var output = document.getElementById("output");
output.innerHTML = input.value;
}
<form>
<input type="text" id="input" placeholder="Enter your name">
<input type="button" id="button" value="enter">
</form>

<h1 id="output">Please Complete Form</h1>

关于javascript - 在输入文本字段上按 Enter 键提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35222651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com