Skip to content Skip to sidebar Skip to footer

How To Call Function When I Press Tab Key In Javascript?

I have a function like that : function whenEmpty(field) { if (field.value == '') { field.style.backgroundColor = '#ffcccc'; alert('Please fill the field.'); field.

Solution 1:

You can add an event listener to the document like so.

document.addEventListener('keyup', function(event) {
  if (event.keyCode == 9) {
     whenEmpty();
  }
});

This will listen for any keyup (keyboard button released) events, and then in the if check what the keycode of the pressed button was. 9 is the keycode for Tab. If you want to pass the field to the function, you could also add the event listener to the input itself. Then access it with event.target


Solution 2:

You can add a keyup listener on body or you can add listener on your table(just if you add tabindex attribute )

// event listener for keyup
function checkTabPress(e) {        
    if (e.keyCode == 9) {
     //call your function whenEmpty()
    }
}

var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);

Post a Comment for "How To Call Function When I Press Tab Key In Javascript?"