Sunday, January 18, 2009

Disabling Enter Causing Submit with jQuery


Recently I was asked to disable the submit event being triggered when the enter key is hit in a textbox input. This is for an ASP.NET MVC application. That means that including this in the site.master will allow identical behaviour across the entire web application.

When you hit enter, the focus will move to the next textbox.

There is also browser sensing code since Firefox needs a different event bound.


jQuery(document).ready(function($) {
   textboxes = $("input:text");

   if ($.browser.mozilla) {
      $(textboxes).keypress(checkForEnter);
   } else {
      $(textboxes).keydown(checkForEnter);
   }

   function checkForEnter(event) {
      if (event.keyCode == 13) {
         currentTextboxNumber = textboxes.index(this);

         if (textboxes[currentTextboxNumber + 1] != null) {
           nextTextbox = textboxes[currentTextboxNumber + 1];
           nextTextbox.select();
      }

         event.preventDefault();
         return false;
      }
   }
});

9 comments:

David Keaveny said...

I don't know about you, but it would be fingernails on a chalkboard to my soul to change such a standard UI convention. Surely by now people are used to using the Tab key to, um, tab between fields, and then Enter key to, um, enter the form. Except of course on Firefox for Mac, where only text fields can be Tabbed to, dropdowns and radio-/check-buttons cannot. UI fail right there too!

Out of interest, what have they asked that the Tab key do instead?

Mana said...

I hear you but they wanted it so I implemented it.

Sometimes it's better to lose the small battles and leave the winning for the ones that matter.

David Keaveny said...

Oh I quite agree; the customer wants, the customer gets (as long as it's not too bad for them!)

Wiggy said...

I wonder though if this would be an obstacle to blind users of the system?

Mana said...

Yes, they wanted it taken out in the end. Sometimes you have to show people before they realise it's not a good idea.

Cogswell said...

any idea how to also disable enter on the radio buttons?

Thanks! awesome script

Preto said...

thanks...works fine in my case!

Preto said...

thanks...works fine in my case!

sarajchipps said...

you rock! thanks, totally stole this.