4

UPDATE: I am constructing the form via Javascript, so the form is not there on page load.

I have an input field with id="input", whenever the enter key is pressed, the form gets submitted. So I tried handling it like this.

$("#input").keydown(function (e) {
    if (e.keyCode == 13) {
        alert("enter pressed");
        return false;
    }
});

However this does not work, there is no alert and the form still gets sent. How do I solve this?

5 Answers5

2

Use preventDefault() to prevent the form from submitting.

$("#input").keydown(function (e) {
  if (e.keyCode == 13) {
    alert("enter pressed");
    e.preventDefault();
  }
});

Example with a form:

$('form').submit(function(e){
  e.preventDefault();
});

https://jsfiddle.net/aya6ockv/

JJJ
  • 3,314
  • 4
  • 29
  • 43
1

Use onkeypress attribute in your input as follows:

<input type="text" onkeypress="myFunction(event)">
<script>
function myFunction(event) {
    var x = event.which || event.keyCode;
    if(x == 13) {
        alert("enter pressed");
        return false;
    }
}
</script>
  • 1
    I get the alert message, however, `return false` is not stopping the form from being submitted –  May 11 '17 at 16:56
0

I would do it like this and change 'form' to #input. Unless you want to stop this enter submission site wide, then this as is should work well.

$("form").bind("keypress", function(e) {
   if (e.keyCode == 13) {
     return false;
   }
});
Mr. CatNaps
  • 121
  • 1
  • 8
0

Just created a JSFiddle that shows that it works. Check it out

$('#input').keydown(function (e) {
  if (e.keyCode == 13) {
    alert('alert pressed');
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form">
  <input text="name" id="input">
  <button type="submit">Submit</button>
</form>
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
  • does this have to go into the document.ready function or can it be an independent function –  May 11 '17 at 13:49
  • I don't understand why this is not working for me, could it be that my form is constructed via Javascript instead of on page load –  May 11 '17 at 13:52
  • even if the form is constructed via Javascript? –  May 11 '17 at 14:06
-1

return false is more efficient than e.preventdefault(). Please look at event.preventDefault() vs. return false

$("#input").keydown(function (e) {
    if (e.which == 13) {
        alert("enter pressed");
        return false;
    }
});
Community
  • 1
  • 1
samnu pel
  • 914
  • 5
  • 12
  • if you are using, you can reliably use "which". i just updated my answer. And I suggest instead of using keydown use "keypress". – samnu pel May 10 '17 at 21:41