I have an HTML form with multiple text inputs. I want to clear the element that had the focus immediately prior to when the 'Clear' button is pressed. How do I get that element in JavaScript?
Note: Reworded to take comments into account.
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
The blur() method removes focus from an element.
To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input.
The hasFocus() method returns a true if the document (or any element in the document) has focus. Otherwise it returns false .
Create a global variable for storing the current focused element's id,
var cur_id;
call one function for onblur
of each of elements and pass id
<input type="text" id="name" name="name" onBlur="setId(this.id)">
and write the set the id to global variable from that function
function setId(id) {
cur_id = id;
}
and write a function for onclick of clear button, like this
function clear() {
document.getElementById(cur_id).value = "";
}
When you click "clear" button, only element focused is "clear" button. You'll have to workaround it. (trigger onblur event)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With