Hong Que
Hong Que

Reputation: 1

Keyup function didn't work with Tab key (jQuery)

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>

Upvotes: 0

Views: 1629

Answers (1)

Shivaji Varma
Shivaji Varma

Reputation: 682

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
    }
  })
})();

Upvotes: 1

Related Questions