Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to make enter behave like tab in dynamic form

form elements

How to make enter behave like tab in dynamic form

by  jonto786  Posted    (Edited  )
I found a solution that seems to work fine with Internet Explorer. The problem I needed to solve was to make the enter-key behave like the tab-key in a form. The problem was that since the form could look different depending on previous user input I was unable to know the tabindex of the next field for sure (the "steps" in the tabindex could be 1, 5 or 10 between form fields). Also I was unable to use the .element[] feature of the form to find the correct (next) field by just getting the next element in the array.
The forms[0] reference of course gets the first form in the document and is hardcoded in this code, you may choose to make a more clever function, I didn't bother...

I trigger this function on the "onKeyup()" event like this (placed in the <form> tag) onkeyup="tabIfEnter(event)".

Here is the Script code to make it work:
[color blue]
function tabIfEnter(event)
{
if(event && event.which)
{
var e=window.event;
var charCode=e.which;
}
else
{
var e=window.event;
var charCode=e.keyCode;
}
if (charCode == 13)
{
var x = document.forms[0].length;
var nextElement = document.forms[0].elements[x-1]; //Gets the last element in the form
var currentTabIndex = window.event.srcElement.getAttribute('tabindex'); // Gets the tabindex of current field

//if current field is the last set focus on the first in the form
if (window.event.srcElement.name == nextElement.name)
{
document.forms[0].elements[0].focus();
return;
}

//find a field that has a tabindex higher than current field and lower than the last (or any found previously)
//by looping through entire form
for(elementnum = 0; elementnum < x; elementnum++)
{
if ((document.forms[0].elements[elementnum].getAttribute('tabindex') > currentTabIndex) &&
(document.forms[0].elements[elementnum].getAttribute('tabindex') < nextElement.getAttribute('tabindex')))
{
//replace with better match than the one we had
nextElement = document.forms[0].elements[elementnum];
}
}
nextElement.focus();
return;
}
else
{
window.event.srcElement.focus(); //set focus on current field
return;
}
}
[/color]
Hope it can save somebody else some time. I haven't tried the script on any other platforms than IE since it is only used in an intranet.

//Jonas
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top