views:

609

answers:

5

I have a form that I use JQuery, I don't think I need to put code in this post, the question is pretty basic.

But I would like to block the form from submitting when people press the Enter Key or the Return Key.

At the same time, I have textareas, where the user will need to be able to press the Enter / Return keys.

+3  A: 

A quick and nasty hack but generally more reliable than trying to block keypresses in every field: add:

<input type="submit" onclick="return false;" />

at the top of the form. The first submit in a form acts as a default button for when Enter is pressed in current browsers, so by neutering it you prevent an Enter-submission from occurring.

Then use CSS to hide and/or move the button so it can't be seen.

It isn't always a good idea to block Enter-submissions though; it's the standard way the browser is expected to work and some users really do want it.

bobince
Thanks, that is what I was looking for. I understand that messing with normal browser actions isn't a good idea, but sometimes you just have to do what the client wants...
WillKop
A: 

set a flag at the document level, submitform = false; validate submissions against this. change the flag in the onclick handler of the submit button.

Devin Ceartas
A: 

Couldn't you add an onsubmit attribute to the form, then check if it was submitted using the enter key?

SeanJA
A: 

You could try this

jQuery(document).ready(function(){
   validSubmit = false;
})

jQuery('myForm textarea').keypress(function(e) {
   if (e.which == 13) {
      validSubmit = true; // if the pressed key is enter, then allow submissions
   }
})

jQuery('myForm').submit(function(){
   if (!validSubmit) {
      return false;  //if submitting the form is not allowed, then cancel submission
   }
})

This cancels all submissions whatsoever unless the enter/return key is pressed on a textarea. If you are using a button, you need to add a function to that too.

jQuery('form button.validSubmit').click(function(){  //or 'form input[type="submit"]'
   validSubmission = true;
})
Mike
A: 

thanks a lot.. i was having a thickbox with a form.. and enter button was taking me out of ajax submit with jquery plugin.. but now.. both the jquery method and hidden submit button worked fine for me.. thanks

saxan
http://makemytaste.com

Saxan Rappai