views:

105

answers:

3

I have HTML:

<input type="text" id="text1" onBlur="focusMe(this.id);" />

and javascript function:

function focusMe(Id)
{
document.getElementById(Id).focus();
}
A: 

I would just pass the control directly. Why pass the ID just to get the control back from it again?

Markup:

<input type="text" id="text1" onBlur="focusMe(this);" />

Javascript:

function focusMe(elem)
{
  elem.focus();
}
Oded
A: 

Well, running your code shows that it doesn't work, and probably with very good reason.

Since I'm here, I should point out that you can actually pass a reference to this rather than this.id and save some hassle:

onBlur="focusMe(this)"

function focusMe(el) {
    el.focus();
}

But it doesn't work anyway, so it's a tad moot.

nickf
+5  A: 

It is possible:

function focusMe(Id) {
    setTimeout(function() {document.getElementById(Id).focus();}, 0);
}

Your script is not working because onBlur is called just before the focus is lost.

Two remarks:

  • you'd better use a reference to the input rather than its id
  • why do this?!
Jerome
+1 on asking why. This is a really bad idea. Very anti-user.
slebetman
If there is only a single text input field, it might make sense to force the focus on it.
Aaron Digulla