Disabling Enter press for form submission

Sometimes, you just gotta disable pressing the Enter key to submit a form. Maybe you are requiring the user to perform certain actions, maybe you are forced to support multiple browsers and pressing Enter doesn’t perform the same way in all browsers. Whatever the case, here’s one way to do it:

First, on your input field, included an onKeyPress attribute, thus:

onkeypress=”return disableEnter(event)”

Then, include a js function disableEnter, thus:

<script language="JavaScript">
<br />function disableEnter(e)
<br />{
<br />&nbsp;&nbsp;&nbsp;&nbsp; var key; &nbsp;&nbsp;&nbsp;&nbsp; 
<br />&nbsp;&nbsp;&nbsp;&nbsp; if(window.event)
<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; key = window.event.keyCode; //IE
<br />&nbsp;&nbsp;&nbsp;&nbsp; else
<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; key = e.which; //firefox &nbsp;&nbsp;&nbsp;&nbsp; 
<br />
<br />&nbsp;&nbsp;&nbsp;&nbsp; return (key != 13);
<br />}
<br />
</script>

Enter should now be disabled for form submission.

Advertisements

About buffalobillion

Web Developer, JavaScript Balrog, Java dude, Ruby/Rails enthusiast. Guitar Playa.
This entry was posted in Web Dev. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s