0

I'm trying to disable Enter key submit on a form but allow the Enter key event to be registered for some other code I have listening. Is this possible?

$('#createPost :input').on("keypress", function(e) {

    if(e.target.id == 'post-author' && e.which == 13){
        e.stopPropagation();
        e.stopImmediatePropagation();
    }
});

Is not working :( it still submits the form

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • Why not just instead prevent the submit event, then submit it manually on the submit button click? I don't like the idea of not being able to submit on pressing enter though. – Kevin B Sep 04 '13 at 22:05
  • Possible duplicate: http://stackoverflow.com/questions/2125470/supress-submit-event-submit-button-enabled-only-if-javascript-is-disabled – fujy Sep 04 '13 at 22:07
  • You could just prevent the default behaviour of the enter key in the other code that listens for keys ? – adeneo Sep 04 '13 at 22:09

1 Answers1

1

You need to call e.preventDefault() to cancel submit action.

return false; from handler also works. And that works in more ancient browsers, even though this is not important with jQuery.

kirilloid
  • 14,011
  • 6
  • 38
  • 52
  • [WRONG, READ BELOW] adding on that: e.stopPropagation() works only on the jquery event chain – Aegis Sep 04 '13 at 22:07
  • Yes and no. This method [do exists](https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation) in browsers, but it has no sense, since `submit` event does not bubble. – kirilloid Sep 04 '13 at 22:08
  • That's cool, but as soon as I e.preventDefault(), it cancels the code I have listening to the Enter key press – benhowdle89 Sep 04 '13 at 22:15
  • Hmm, `preventDefault` w/o `stopPropagation` should work. At least, on single element when no delegation is used. – kirilloid Sep 04 '13 at 22:17