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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.