4

I am using this code to handle keydown event for tab and enter key for an input.

$(document).on('keydown', ".className" , function(e) {
  var keyCode = e.keyCode || e.which; 

  alert(keyCode) // does not work for 'next'

  if (keyCode == 9) { //tab key // does not work for 'next'
    e.preventDefault(); 
    if( $(this).parents('tr').next('tr').length == 0){
     $('.add_info').click();  
    }
    $(this).parents('tr').next('tr').find('input:first').focus();
  }

  if (keyCode == 13) { //enter key
    e.preventDefault(); 
        $('.anotherField').focus();
  }
});

The code for the tab key does not work on a mobile's browser. The numeric keyboard shows up for the .className fields as the input type is number, so it has Next key along with other keys. I tried alert(keyCode) just to get the keycode for Next, but the event does not trigger. Is there anyway I could override the default behavior of the Next key?

Mehravish Temkar
  • 4,275
  • 3
  • 25
  • 44
  • Take a look to this [answer](https://stackoverflow.com/questions/7060750/detect-the-enter-key-in-a-text-input-field) – gaetanoM Dec 04 '20 at 15:28
  • @gaetanoM the code is working fine handling the event for other keys, only doesn't trigger for `Next` on a soft-keyboard for mobile or tablets – Mehravish Temkar Dec 04 '20 at 15:33

1 Answers1

2

I could not find a way to trigger the event for Next, so I tried a workaround.

The Next focuses on the next element on the page. I set a flag when my input lost focus. When the next element is focused right after this element(if the flag is set) then I trigger the code block for tab (what I intend to do when the tab key is pressed in that input.

var from_class_name = 0;
$(document).on('keydown', ".className" , function(e) {
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { //tab key // does not work for 'next'
    e.preventDefault(); 
    if( $(this).parents('tr').next('tr').length == 0){
     from_class_name= 0;
     $('.add_info').click();  
    }
    $(this).parents('tr').next('tr').find('input:first').focus();
  }

  if (keyCode == 13) { //enter key
    e.preventDefault(); 
    from_class_name= 0;
    $('.anotherField').focus();
  }
});


$('#divid').on('focusout', '.className', function(){
    if( $(this).parents('tr').next('tr').length == 0){
        from_class_name = 1;
    }
});
$('.otherelement1, .otherelement2, .otherelement3, .otherelement4').on('focus', function(){
    from_class_name = 0;
});

$('.nextElement').on('focus', function(){ //element which is focused when 'Next' is used
    if(from_class_name == 1) { // the value is 1 when the .className loses focus and no other fields are focused right after it except .nextElement
        from_class_name = 0;
        $('.add_info').click();
    }
});
Mehravish Temkar
  • 4,275
  • 3
  • 25
  • 44