最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to submit form by pressing enter or pressing submit button? - Stack Overflow

programmeradmin3浏览0评论

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? 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 = '.html';
return false;


}

}
</script>

Thanks,

Tom

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? 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./benoit.html';
return false;


}

}
</script>

Thanks,

Tom

Share Improve this question asked Jul 22, 2017 at 13:27 Tom DaviesTom Davies 512 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Instead of using <input type="button" />, use <input type="submit" /> to send the form.

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:

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./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 ment I entered -->
<input type="submit" value="Submeter" onclick="myFunction()" />
</form>

发布评论

评论列表(0)

  1. 暂无评论