How can I tell if a certain textbox has focus or not? I'm writing in C# in .NET.
+3
A:
Because performance can be a problem with generic solutions, the easiest thing I've come across so far is as follows:
- Subscribe to the onFocus event of each control you care about.
- In the onFocus handler, set a global variable (maybe "lastFocusElement") to the element that just received focus.
- When you need to know that a certain control has focus, compare against the "lastFocusElement" variable.
John Fisher
2009-10-07 17:05:07
Here, for C#, I have the `Enter` event actually, not onFocus (and the OnEnter Method). But that's the idea, I usually do that when I need to keep track of the focused element and it works fine.
RedGlyph
2009-10-07 17:30:22
+4
A:
You would have to use the javascript events OnFocus
and OnBlur
, and set a variable of some sort. Basically:
<script>
var lastFocus=null;
function DoesControlHaveFocus(var control){return control==lastFocus;}
</script>
<input type="text" onfocus="lastFocus=this" onblur="lastFocus=null"/>
FOR A version that would work in the code-behind, you would set a hidden field to the ID of the control in the OnFocus command, which you could then check.
Erich
2009-10-07 17:05:40
I think this will be my answer. I didn't get a chance to try it though but it seems right. +1 to you.
Eric
2009-10-07 17:44:25