0

I have a problem with Tab key in jQuery. The function keyup of the Tab key doesn't working in anycase. Whatever I wrote in the function, it didn't work, only focus on the next textbox.

I tried this:

$('#sn_c3_scan').keyup(function(event) {
        if (event.key == "Tab") {
            alert('haha');
        }
 });

And also this:

$('#sn_c3_scan').keyup(function(event) {
    if (event.keyCode == "9") {
        alert('haha');
    }
});

By the way, the keydown event still worked. But because the keyup didn't work, anything I wrote about changing focus to another control will be wasted when the key released (because it automatically changed the focus to next control - which I didn't want).

Anybody have any idea?

By the way, this is my HTML for the textbox:

    <div class="row c3">
        <div class="col-md-3">
            <b>Serial (S/N):</b> 
        </div> 
        <div class="col-md-9"> 
            <input type="text" id = "sn_c3_scan" class="form-control" autofocus> 
        </div> 
   </div>

    <div class="row c3">
        <div class="col-md-3">
            <b>AAAA:</b> 
        </div> 
        <div class="col-md-9"> 
            <input type="text" id = "sn_c3_scan2" class="form-control"> 
        </div> 
   </div>
Hong Que
  • 1
  • 3

1 Answers1

1

On tab keydown the focus switchs to next element, so keyup will not fire on the input field. You can instead remember the keydown of 'tab' event and execute your code on keyup on 'document'.

jsbin link: https://output.jsbin.com/tinoroxopu/3

(function(){
  var tabPress = false;
  $('#sn_c3_scan').keydown(function(event) {
    if (event.keyCode == "9") {
       tabPress = true;
    }
  });
  $(document).on('keyup', function(){
     if(tabPress){
      alert('hello');
      tabPress = false; //reset
    }
  })
})();
Shivaji Varma
  • 690
  • 13
  • 24
  • Thanks. I don't know why but it still didn't work. It seems like anything on 'keyup' didn't work on Tab key. 'Keydown' worked normally. And the 'keyup' still worked with every other key, but Tab. ToT It is so strange. – Hong Que Jun 07 '18 at 05:19
  • Well, but the jsbinlink really works. Ow! What happen with mine? T_T – Hong Que Jun 07 '18 at 05:27
  • Keyup is happening on next input field/element, because focus has switched on keydown to next element. – Shivaji Varma Jun 07 '18 at 05:29
  • Yeah, but when I use the code in jssbinlink into my project, it didn't work. I don't know why. Haizzz... But it actually work in the link you sent me. Maybe there is something wrong in my project. – Hong Que Jun 07 '18 at 05:49
  • The jsbin link doesn't always work either. I just tried again & it just change to the next control on the Tab keyup. It is really strange, guy. – Hong Que Jun 07 '18 at 06:13