在输入文本字段上按 Enter 以提交表单

Press enter on input text field to submit form

在我的代码中,我希望能够按 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>

试试这个...

<input type="text" id="input" placeholder="Enter your name" onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }">

可能会有帮助。