I need to know when a particular input field loses focus, what object has focus. I can do an on blur function to determine when the field loses focus, but I can't figure out how to get the ID of the object that has focus.
Basically, I have a field doing something when you're in it and I need to determine when someone has clicked into another field so it will stop doing that thing.
Something like this:
<input id="field1">
<input id="field2>
$("#field2").on("blur", function() {
if $(":hasfocus").id() === "field1" {
// do something
}
});
What is the best way to go about this without trying to do some global focus tracker?
Response to comments:
A) An on blur doesn't actually work for this situation. I specifically need to know the ID of the object that has focus once this one loses focus.
B) $(":focus") is something I looked at but it didn't occur to me that it would return multiple objects. I tried $(":focus").attr("id") which always returned body, which I now realize is because it's only getting the ID of the last object in that list. Thanks!
C) $(":focus") is returning nothing. The array length is 0. Not quite sure why that would be.
In the end, the best solution was to put in another focus handler for :input.
I just check for $(":input").on("focus") and if the ID does not match my input field(s), then it completes the processing.
I have a function that replaces an input field with another set of fields for an IP address entry. What I was trying to do is detect if someone tabbed or clicked out of my field so that I could write it back to the original input field.
The :input focus resolved that issue rather than trying to determine things when the fields I care about lose focus.