简体   繁体   English

如何通过按Enter或提交按钮提交表单?

[英]How to submit form by pressing enter or pressing submit button?

I've created a form, but it only submits if I press the button Submit... How can I make it also submit if the Enter key is pressed? 我已经创建了一个表单,但是仅当我按下按钮Submit ...时才提交表单。如果按下Enter键,如何使它也提交? Here is my form's code: 这是我表格的代码:

<form method="POST" id="form01">
<textarea name="inputBox123" id="myTextarea" style="white-space:nowrap;">
</textarea>
<input type="button" value="Submeter" onclick="myFunction()" />
</form>

<script type="text/javascript">

function myFunction(val) {

var testThis = document.getElementById("myTextarea").value;

if ( testThis.indexOf("launch") > -1 ) {
window.location = 'http://www.cateto.weebly.com/benoit.html';
return false;


}

}
</script>

Thanks, 谢谢,

Tom 汤姆

Instead of using <input type="button" /> , use <input type="submit" /> to send the form. 代替使用<input type="button" /> ,而使用<input type="submit" />发送表单。

The enter button should submit the form by default. 输入按钮默认应提交表单。

You should attach event listener to textarea tag and listen for keypress and when Enter is pressed you invoke your function: 您应该将事件侦听器附加到textarea标记上,并监听keypress然后按Enter键即可调用函数:

 var textarea = document.querySelector("textarea");//get textarea tag //NOW replace this with: var input = document.getElementById("myTextarea") //BELOW change textarea with input textarea.addEventListener("keypress", function(e){ console.log(e.which, e.target.value); if(e.which === 13)//code number for enter key myFunction(e.target.value);//run function with value }); function myFunction(val) { var testThis = document.getElementById("myTextarea").value; if ( testThis.indexOf("launch") > -1 ) { window.location = 'http://www.cateto.weebly.com/benoit.html'; return false; } } 
 <form method="POST" id="form01"> <textarea name="inputBox123" id="myTextarea" style="white-space:nowrap;"> </textarea> <!-- change above with input in the comment I entered --> <input type="submit" value="Submeter" onclick="myFunction()" /> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM