问题描述:

I need to submit form by clicking submit button only. I don't want to submit form by pressing enter.

Here is my code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<script>

$('#regForm').on('keyup keypress', function(e) {

var keyCode = e.keyCode || e.which;

if (keyCode === 13) {

e.preventDefault();

return false;

}

});

</script>

<form action="2.php" method="get" id="regForm">

<input name="a" type="text" />

<input name="b" type="text" />

<input name="sub" type="submit" value="Submit" />

</form>

2.php contains var_dump($_GET); But it will submit form after pressing enter key and clicking submit button

网友答案:

You are almost right, but small mistake. You need to delegate those events on the inputs and not on the <form> itself:

$('#regForm').on('keyup keypress', "input", function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

The above code will not register Enter key.

The same code as a working snippet:

$(function () {
  $('#regForm').on('keyup keypress', "input", function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode === 13) {
      e.preventDefault();
      return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="2.php" method="get" id="regForm">
  <input name="a" type="text" />
  <input name="b" type="text" />
  <input name="sub" type="submit" value="Submit" />
</form>
相关阅读:
Top