Dojo: preventing form submit on Enter

Posted 14:28, on 14/2/2011 in Web

If you've got some AJAX functionality inside a standard form (e.g. an address lookup feature where people type in their postcode and click a button) then there's a temptation for people to hit 'Enter' to perform the search. By default this will submit the whole form, which isn't what you want.

Catching the 'Enter' key press is fairly easy to do with some inline Javascript, but it can easily be done unobtrusively with Dojo as well:

dojo.addOnLoad(
	function() {
		dojo.connect(dojo.byId('postcode'), 'onkeydown', function(event){
			if (event.keyCode == dojo.keys.ENTER) {
				// CALL AJAX CODE HERE

				dojo.stopEvent(event);
			}
		});
	}
);

I found that 'onkeyup' as the event doesn't work here - the code runs but doesn't prevent the submission, so stick to onkeydown.

Comments (2)

Comments

Zimzat
22:10, on 21/4/2011
The keyup event always happens after the default (browser) event occurs. Only keydown and keypress can potentially intercept an event.
Tim Fountain
11:24, on 26/4/2011
That makes a lot of sense - thanks for the tip.

Add Comment

External articles that may be of interest:

Rasmus - PHP Performance

Full video of a talk Rasmus gave at Digg HQ on PHP performance. After a brief look at PHP 5.3's new features he sets about improving the performance of an out-of-the-box Wordpress installation.

Adobe releases 64-bit flash player for Linux

Adobe have released an alpha of their 64-bit flash player for Linux (I believe this is the first 64-bit player they've done on any platform, it's not available for Windows or Mac yet). And it works great. It may be an alpha but so far I've found it considerably more stable than the released 32-bit wrapper version. It also uses considerably less CPU power. Easy installation instructions via. this blog entry.

MS Office in the browser

The most interesting thing about this announcement is that MS say the system will work in Firefox and Safari as well as IE. The Microsoft of 10 years ago would have used proprietary IE only code and used it as a way to leverage IE market share.

The Future of Advertising, Branding, Media and Communications

Video of a very interesting talk by Gerd Leonhard on the future of the media industry, and content on the Internet.

Future of web browsing from Mozilla Labs

Some interesting ideas about how web browsing might look in the future (watch the first video).