views:

1619

answers:

4

I'm looking to create a form where pressing the enter key causes focus to go to the "next" form element on the page. The solution I keep finding on the web is...

 <body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}">

Unfortunately, that only seems to work in IE. So the real meat of this question is if anybody knows of a solution that works for FF and Chrome? Additionally, I'd rather not have to add onkeydown events to the form elements themselves, but if that's the only way, it will have to do.

This issue is similar to question 905222, but deserving of it's own question in my opinion.

Edit: also, I've seen people bring up the issue that this isn't good style, as it diverges from form behavior that users are used to. I agree! It's a client request :(

+2  A: 

You could programatically iterate the form elements adding the onkeydown handler as you go. This way you can reuse the code.

Byron Whitlock
This is what I ended up doing. Thanks!
Ross
A: 

If you can I would reconsider doing this: the default action of pressing while in a form submits the form and anything you do to change this default action / expected behaviour could cause some usability issues with the site.

Ian Oxley
Normally I would agree, but our app lets users set stuff like this separately for their own accounts, and the client is offering money for it, so I don't think we can justify holding our ground.
Ross
A: 

I had a simular need. Here is what I did:

  <script type="text/javascript" language="javascript">
    function convertEnterToTab() {
      if(event.keyCode==13) {
        event.keyCode = 9;
      }
    }
    document.onkeydown = convertEnterToTab;    
  </script>
Bobby Ortiz
A: 

Changing this behaviour actually creates a far better user experience than the default behaviour implemented natively. Consider that the behaviour of the enter key is already inconsistent from the user's point of view, because in a single line input, enter tends to submit a form, while in a multi-line textarea, it simply adds a newline to the contents of the field.

I recently did it like this (uses jQuery):

$('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
 if (e.keyCode==13) {
  var focusable = $('input,a,select,button,textarea').filter(':visible');
  focusable.eq(focusable.index(this)+1).focus();
  return false;
 }
});

This is not terribly efficient, but works well enough and is reliable - just add the 'enterastab' class to any input element that should behave in this way.

Andrew