开发者

jQuery: keyup for TAB-key?

开发者 https://www.devze.com 2023-02-05 20:07 出处:网络
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

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 nothi开发者_JAVA技巧ng 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.


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.


e = e || window.event;
if(e.keyCode == 9)
 alert("Tab pressed");

Try this


if nothing happens no matter what key you press, perhaps there is something wrong with the selector you are using? Can you verify you are selecting properly, perhaps with something like:

console.log($('/* my inputs */').length);
0

精彩评论

暂无评论...
验证码 换一张
取 消