Sohail Faruqui
Sohail Faruqui

Reputation: 452

How to access the Event Object in focusout Event Handler

Sorry to ask such elementary question. I am learning Javascript and jQuery.

I have a popup with 3 input fields say ETD, ETA and duration. I am trying to calculate duration on focusout from ETD and ETA and there will be an AjaxCall in which we do the calculation and other stuff. The issue is whenever I press the Tab Key(focusing out of ETD or ETA) the focus will be moved out of popup and will moved to main window.

I am trying to set focus forcefully on these input fields on success of ajax call. I am trying to achieve this using flags, for example if focusout happened on ETD then ETDFlag will be true and I'll check this flag on onsuccess of ajax call, so if ETDFlag is true I'll put focus on ETA and so on, but the issue is even if I focusout of the field by clicking out of field the focus will go to next field, so I need to set flags only when Tab Key is pressed.

Below is the sample code:

$("#ETD").focusout( function (event) {  
    var keyCode=event.keyCode || event.which;
    if(keyCode == 9){
        ETD= true;
        ETA= false;
    }       
    calculateDuration();

I am not getting the event object inside as when I tried alert(event); the output was [object Object].

But something like:

alert(e.target.id)

Will show the id of the field. e.g. ETD

Please help and tell me what is wrong. I am new in Javascript so not able to understand.

Edited for more clarification

The goal is to go to the next input when user presses the Tab button. As mentioned current behaviour is after pressing tab (focusout) an ajax call will happen to calculate the duration field value and focus will move out of popup to main window! So the main purpose of having event object is to get the keycode of the Tab button:

 var keyCode=event.keyCode || event.which;
 If(keyCode==9)   //tab key code
 {Then make some flag true}

But on press of Tab key it never come inside if condition!

Edited for more clarification 2

var keyCode=event.keyCode || event.which;

I tried to use above code on a keyup event and "keyCode" is able to capture almost all the keys except Tab keys!

Upvotes: 0

Views: 2247

Answers (2)

andrex
andrex

Reputation: 1032

I think you need keyup or keydown and not focusout then you do your process.

$(document).ready(function(){ 
   $("#ETD").bind('keydown', function (event) {  
      if(event.keyCode == 9){
          alert('its a tab');
          // you do your process here
      }       
   });
});

SEE DEMO

Focusout is not a keyboard events so you can't get any keycode from it. Read more about keyboard events here

Upvotes: 2

SLaks
SLaks

Reputation: 888195

You are getting the event object.

alert() will convert its argument to a string.
jQuery's event object does not override toString(), so you get the default of [object Object].

Upvotes: 2

Related Questions