Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: keyup for TAB-key?

Tags:

jquery

tabs

So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

$('/* my inputs */').keyup(function(e) {    console.log('keyup called');    var code = e.keyCode || e.which;    if (code == '9') {      console.log('Tab pressed');    } }); 

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

like image 317
qwerty Avatar asked Jan 21 '11 18:01

qwerty


1 Answers

My hunch is that when you press the tab key, your form's input loses focus, before the keyup happens. Try changing the binding to the body, like this:

 $('body').keyup(function(e) {     console.log('keyup called');     var code = e.keyCode || e.which;     if (code == '9') {     alert('Tab pressed');     }  }); 

Then, if that works (it does for me) try changing the binding to keyDown, instead, and return false. That way you can implement your own custom behavior.

$('.yourSelector').keydown(function(e) {    console.log('keyup called');    var code = e.keyCode || e.which;    if (code == '9') {      alert('Tab pressed');     return false;    }  }); 

One of these two should work... if it's body, you could attach a keydown handler on body, then if it's tab, find the field with focus (I think there's function .hasFocus()?), and if it's the one you want, proceed and return false. Otherwise, let the browser do its thing.

If you wanted to update the field WITH a tab character, try this in your callback:

var theVal = $(this).val(); theVal = theVal + ' '; $(this).val(theVal); 

Haven't tested it, but it should work. You could also append 3 or 4 spaces instead of the tab character, if it's giving you trouble.

like image 101
Chris Ladd Avatar answered Sep 21 '22 01:09

Chris Ladd