3

how can we prevent a form from being submitted while pressing enter key.

Actually I have a text box and on entering a value on that textbox and clicking enter the textbox2 will get focused.

By default on clicking the enter button the form will get submitted. So I can not get the out put. I wrote return false on onclick event of the submit button then it works. So I would like to know how can we prevent a form submission while pressing enter.

Varada
  • 16,026
  • 13
  • 48
  • 69

4 Answers4

2

Without looking up the actual code, here's the basic theory behind how I'd do it:

Define an event handler on the document for a key being pressed to call a function.

If the key that triggered the event is the enter/return key, return false, otherwise return true.

EDIT: Looks like you already found the answer (as well as some code to do it), so my answer is somewhat unnecessary now.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

Writing 'onKeyPress' of the form like " { var key; if(window.event) key = window.event.keyCode; else key = e.which; //firefox return (key != 13); } " will work.

Varada
  • 16,026
  • 13
  • 48
  • 69
0

what i do is add onsubmit="return false;" to the <form> tag. this will also disable the submit button however to create a working submit button use

<input type="button" value="Submit" onclick="javascript:document.form.submit();" />
psiclops
  • 1
  • 2
-1

This should work

<form onsubmit="return false;">
    //Form elements
</form>
LeeR
  • 1,609
  • 11
  • 29
  • Have you tested this? Seems like that would prevent you from submitting the form in any way, not just by pressing Enter. I could be wrong though. – Anthony Grist Jun 09 '11 at 10:32
  • It will prevent the form from submitting. – Varada Jun 09 '11 at 10:33
  • writing 'onKeyPress' of the form like " { var key; if(window.event) key = window.event.keyCode; else key = e.which; //firefox return (key != 13); } " this will work. – Varada Jun 09 '11 at 10:33
  • Yes, but if you read, he already has a return false on the submit button, so one can assume that he doesn't actually want to submit the form the normal way – LeeR Jun 09 '11 at 11:13