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

I've created a form, but it only submits if I press the button Submit... How can I make it also su

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744906175a4600270.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信