Dojo: preventing form submit on Enter

Posted

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.ready(
    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.

Update: Here's the AMD (Dojo 1.7+) equivalent of the same thing:

require(['dojo/ready', 'dojo/dom', 'dojo/on', 'dojo/keys'], function(ready, dom, on, keys){
    ready(function(){
        on(dom.byId('postcode'), 'keydown', function(e){
           if (e.keyCode == keys.ENTER) {
               // AJAX stuff here
 
               event.stop(e);
           }
        });
    });
});
Comments (5)

Comments

Zimzat
21st Apr, 2011

The keyup event always happens after the default (browser) event occurs. Only keydown and keypress can potentially intercept an event.

Tim Fountain
26th Apr, 2011

Makes sense - thanks for the tip.

Alina
18th Jul, 2012

Thanks for your tips.It's very userful

Richard Ayotte
31st Mar, 2013

Reply to a really old post but Google sent me here so must still be good.

Minor correction on the AMD update. You need require 'dojo/keys' as well.

require(['dojo/ready', 'dojo/dom', 'dojo/on', 'dojo/keys'], function(ready, dom, on, keys)
Tim Fountain
8th Apr, 2013

Thanks, I've updated the post.

Add Comment

(Never shown on the site)

(Newlines preserved, format with Markdown)