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!

Setting focus .. this should be simple

Status
Not open for further replies.

rpeters74

Programmer
May 24, 2002
46
0
0
US
Simple scenario:
You have 3 textboxes on the screen (txt1, txt2, txt3). When the focus leaves (onBlur) txt1 I want to manually set the focus to txt2 only if the reason focus was lost on txt1 was due to the tab button.

onBlur event has a keyCode (event.keyCode) of zero (0) (tab key keyCode is 9).

=========

Below does not work because txt2 gets focus before the tab key is finsihed being pressed. The implicit event handler sees the focus of the cursor as txt2 then tabs to txt3.

<script>
function doTab(evt)
{
if (evt.keyCode == 9)
{
document.all.txt2.focus();
}
}
</script>

<input type="text" id="txt1" onkeyup="doTab(event);">
<input type="text" id="txt2">
<input type="text" id="txt3">

========

This is an over-simplified example. I realize that in this scenario I could let tabbing work as usual but my "real-world" need for this behavior is much more complex.

Thank you for any help.
 
From the top of my head, you would need to return false (cancelled) from the event capture function in order to prevent further handlers-in-chain seeing the event. You might also need to do that for the keyPress rather than keyUp event (but this is pure speculation). The problem comes in that tab-navigation is an undefined browser-implemented thing - code can be used to define a tabbing order, but not the triggering event. It's up to each browser whether or not to let you intercept tabbing at all.
 
Why use JavaScript? Just set the tabindex of the textboxes.

Adam
 
Code:
<script>
function doTab(nextBox){
  if(event.keyCode == 9){
    document.getElementById(nextBox).focus();
    return false;
  }
  return true;
}
</script>

<input type="text" id="txt1" onkeydown="return doTab('txt2');">
<input type="text" id="txt2" onkeydown="return doTab('txt3');">
<input type="text" id="txt3">
See faq183-874 for more info.

Adam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top