Salman Virk
Salman Virk

Reputation: 12327

In JQuery, how to read the element in focus right now?

There is one text input field and one button.

<input type="text" id="myInput" onblur="saveValue();" />    
<input type="button" id="myButton" />

On Blur event ( input field ), a function ( saveValue) is called. I do not want to call that function if the current focus is the button (myButton).

How can I do it in JQuery?

Upvotes: 0

Views: 875

Answers (5)

FutureBoy
FutureBoy

Reputation: 1

Not sure if I've missed something, but why not just bind the blur event to the input field only:

$("#yourInputId").live("blur", function()
{
  saveValue();
});

Upvotes: 0

Methee
Methee

Reputation: 116

I'm not sure if I understand your question correctly. Here is my attempt: Create the css class for the input text and use jquery to refer it that way.

Here is the code sample:

<input type="text" id="txtName" class="input-text" />
<input type="submit" value="Submit"/>

<script type="text/javascript">
$(function(){
  $('.input-text').blur(function(){
    var $this = $(this);
    //Call function save value by passing the reference of the current object
    SaveValue($this);
  });
});
</script>

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238115

You cannot reliably do this, because one element is blurred before the next is focused. The closest approximation would be to set a timeout that you clear if the button is focused:

$(document).ready(function(){
    var timer;

    $('input').blur(function(){
        timer = setTimeout(saveValue, 100);
    });

    $('#myButton').focus(function(){
        clearTimeout(timer);
    });
}); 

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23114

You can simply try..

$(':focus').each(function(){    
   if($(this).attr('id') == 'myButton'){
     //do stuff here
   } 
});

This post at the jquery forum suggests that this works in most cases.

Upvotes: 0

Ian Henry
Ian Henry

Reputation: 22433

You can try:

if(!$('#myButton').is(':focus'))
    ...

Upvotes: 0

Related Questions