• Skip to content
  • Skip to menu

Barattalo

code snippets, classes and other stuff for developers 

Rss 2.0

  • Home
  • Me
  • Mini Bots PHP Class
  • Facebook Connect Tutorial
  • HTML fixer

Feb 16 2010

How to capture enter key pressed in a form (JavaScript)

Category: Html,Javascript — Giulio Pons @ 12:08 pm

Suppose you have a login form and you want to send the form when user press enter on his keyboard and not only by clicking on the submit button.
This can be achieved capturing a specific event when the user is typing. We have to capture the keypress event and listen to trigger an action when the enter key is pressed.
In the html form we have to add the “onkeypress” attribute that will contain a call to a javascript fnction that to the job.
The javascript function receive also a string parameter, so you can customize and reuse this code (it’s the ‘formid’ parameter).
The “evt” and “thisObj” parameters return the event handler and the object (the input type) that made the call to the function. The event parameter is important, the object that calls the fnction is not important as parameter since it’s used only to blur the input field.

Here is the javascript function that handle the event:

<script type="text/javascript">
	function submitonenter(formid,evt,thisObj) {
		evt = (evt) ? evt : ((window.event) ? window.event : "")
		if (evt) {
			// process event here
			if ( evt.keyCode==13 || evt.which==13 ) {
				thisObj.blur();
				document.getElementById(formid).submit();
			}
		}
	}
</script>

This is the html form with the “onkeypress” listener:

<form id='formlogin' action='file.php' method='post'>
	<input type='text' name='username' />
	<input name='pass' type='password' onkeypress="submitonenter('formlogin',event,this)" />
	<input type='submit' value='login'/>
</form>
Share

Tags: event, events, events handller, keypress, login, login form

Comments (0)



  • Categories
    • Asp
    • Css
    • Facebook
    • Google Maps
    • Html
    • Javascript
    • MsSQL
    • MySql
    • Php
    • Spiders & web bots
    • Uncategorized
  • Blogroll
    • Date Concerti
    • Fabrizio La Scimmia
    • Il Bloggatore
    • Ku ku photos
    • Me on Rockit
    • Rockit.it
    • Twirl.it
  • Print and study
    • Building website for iphone
    • Seo staff in Italian
  • Things to test
    • Building website for iphone
    • Counter with Google Analytics
    • htaccess mp3
    • Open inviter
  • Tags
    • Php
    • Spiders & web bots
    • Javascript
    • Spider
    • curl
    • MySql
    • Regular expression
    • spiders
    • Php
    • bot
    • programming
    • Google Maps
    • webbot
    • Web bot
    • Google Maps

top

Powered by WordPress and Stardust

Created by Tommaso Baldovino