1

I do not want to submit a form $.ajax({}) when the enter key is hit, but with clicking the submit button. Tried it with

$('#SubmitButton').click(function(event){

 if(event.keyCode==13) {
  //do something
 }

});

How do I get the above done.

Thanks Jean

X10nD
  • 21,638
  • 45
  • 111
  • 152
  • Already anwered: http://stackoverflow.com/questions/895171/prevent-users-from-submitting-form-by-hitting-enter – mdrg Jan 24 '11 at 15:36

2 Answers2

3

Well, you don't have a key- or charCode in event.which within a click event handler, so this doesn't make much sense at all. You would need to bind a keypress event to one or more input-text controls, where the user may type in (and therefore, trigger a return).

$('input:text').bind('keypress', function(e) {
   if( e.which === 13 )
       return false;
});

returning false from an event handler causes two things:

  • .preventDefault() is called on the event object
  • .stopPropagation() is called on the event object

that should stop the return from bubbling up to your <form> node, which in turn prevents the submit. So, it's actually enough to call e.stopPropagation() here.

jAndy
  • 231,737
  • 57
  • 305
  • 359
1

I would try doing the same thing but binding it with .submit() to the form. You can then return false, or whatever you need to do.

EDIT: I'm leaving this here, because it's useful. But I soon realized that not for this question, since I don't think you can track keypresses with this method. I blame this on just waking up and having not really touched JavaScript in awhile. Sorry for any confusion!

TNi
  • 16,070
  • 3
  • 22
  • 20