faqts : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

206 of 215 people (96%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I let the enter key tab to the next input field?
How can I let the enter key tab to the next input field?

Nov 13th, 2002 08:10
Michaeljon Murphy, Martin Honnen,


NN4+ and IE4+ allow capturing key events on text input fields and text 
areas. By capturing
  onkeydown
and checking for the return key's keycode 13 and then searching the 
next form element you can achieve the effect:

<HTML>
<HEAD>
<SCRIPT>
function getNextElement(field) {
  var fieldFound = false;
  var form = field.form;
  for (var e = 0; e < form.elements.length; e++) {
    if (fieldFound && form.elements[e].type != 'hidden')
      break;
    if (field == form.elements[e])
      fieldFound = true;
  }
  return form.elements[e % form.elements.length];
}
function tabOnEnter (field, evt) {
  var keyCode = document.layers ? evt.which : document.all ? 
evt.keyCode : evt.keyCode;
  if (keyCode != 13)
    return true;
  else {
    getNextElement(field).focus();
    getNextElement(field).select();
    return false;
  }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm" ONSUBMIT="if (!this.submitted) return false; else 
return true;">
<INPUT TYPE="text" NAME="field0"
       ONKEYDOWN="return tabOnEnter (this, event);"
>
<BR>
<INPUT TYPE="text" NAME="field1"
       ONKEYDOWN="return tabOnEnter (this, event);"
>
<BR>
<INPUT TYPE="text" NAME="field2"
       ONKEYDOWN="return tabOnEnter (this, event);"
>
<BR>
<INPUT TYPE="submit"
       ONCLICK="this.form.submitted = true;"
>
</FORM>
</BODY>
</HTML>

The only difference for the browsers is that NN4 keeps the key code in
  event.which
while IE4/5 and NN6 keep it in 
  event.keyCode

This version of the answer includes a change to the getNextElement that 
makes it return the next non-hidden field element on the page.  You 
can't set the focus to a hidden field, so the prior version caused an 
error when a hidden field was next.

This version also selects the field being "tabbed" to, so it looks more 
like the action of a tab.