sam sam - 11 months ago 52
jQuery Question

How to get Id of focused element in javascript

My title might not really express what i want to achieve so i hope reader can go through my question first.
I have many input on my page with different id, i want to get the ID of the particular input that get user focus and fire an event when this input loses focus. i can achieve this by explicitly state the ID and attach onblur event handler to it but this will result in writing a bulk of codes as i have too many input on the same page. now i have this below code

var \$Title = $('#draft-product_title')
eventId =;

this is one of my input and i have more that 30 input so i have to make copy of it 30 time which is so crazy i need a way to make it so flexible, i tried this too but no luck

var \$selectorId;
$('body').on('click',function(event) {
\$focusElementId =;
\$selectorId = ('#'+\$focusElementId)

eventId =;

but this code error selector id not define but the
as it define
any help on how to make this work, am also open to any other idea, thaks


Use :input selector to select all input element

this context in event-handler will be element on which event is invoked hence will return id property of the element or ""(empty)

$(':input').on('focus', function() {
}).on('blur', function() {
<script src=""></script>
<form action="action_page.php">
  First name:
  <input type="text" id="name" value="Mickey">
  <br>Last name:
  <input type="text" name="lastname" id="lastname" value="Mouse">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  <input type="submit" value="Submit">