faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

164 of 193 people (85%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I prevent a form being submitted when enter is pressed inside a text field?
How can I prevent a form being submitted when enter is pressed inside a text field?

May 24th, 2000 14:38
Michel Plungjan, Martin Honnen,


If a FORM contains a single text field pressing enter inside it submits 
the FORM. You can prevent that by letting your submit buttons set a 
flag on the FORM which the onsubmit handler checks. That way enter keys 
in the text field are ignored.
<FORM NAME="aForm" ACTION="whatever"
      ONSUBMIT="if (this.submitted) return true; else return false;">
<INPUT TYPE="text" NAME="god" VALUE="Kibo">
<INPUT TYPE="submit" ONCLICK="this.form.submitted = true; return true;">
</FORM>
Add such an onclick handler for all submit buttons you have.
If there are more than one text or password field on the form, IE will 
click the submit button for you on enter. 
Change 
<INPUT TYPE="submit" ONCLICK="this.form.submitted = true; return true;">
to
<INPUT TYPE="button" ONCLICK="this.form.submitted = true; 
this.form.submit(); return true;">
If you have an onSubmit event handler, you will need to copy it to the 
button and test for NOT IE since netscape will not execute onSubmit when 
the form has been submitted by script. The test in the onSubmit can stay 
for IE, netscape will ignore it - if you want to be sure, test the 
browser version