How can I delay moving to the next input field when the TAB button is pressed?

657 views Asked by At

I was hoping I could get some help with a problem I've been having. I would like to set a small delay when the user presses the TAB button before the next input field found on the webpage is selected. The reason for this is that I am using AJAX to build an order form field, with expandable and collapsible tables that will be taking input from the user.

I have it set up using onfocusout to call a function that expands the table below the current table the user is in after they leave the last field, and would like the first input field to be auto selected right after. Everything works as should when the user exits the last field of a table by clicking out of it, but when tabbing out of it I believe there is a problem because there is not a field to be tabbed to until after it retrieves the next table to display using AJAX.

I can provide code if needed, but I think I'm missing something, rather than having a mistake somewhere. Help would be appreciated, and I'd be more than happy to clarify anything that is unclear. Thank you!

1

There are 1 answers

3
iamjpg On

So, I've created a very basic example of how this can work. My example only accounts for inputs, but you can play with the code to do what you need.

Warning: Preventing natural browser behavior can be tricky so pay attention to other issues this could cause.

Here is a Fiddle showing how you can do this: https://jsfiddle.net/iamjpg/wme339h9/

document.onkeydown = TabExample;

// Basic function
function TabExample(evt) {
    // Capture event
  var evt = (evt) ? evt : ((event) ? event : null);
  // Tab keycode constant
  var tabKey = 9;
  // If key is tab...
  if (evt.keyCode == tabKey) {
    // Prevent the next focus.
    evt.preventDefault()
    // Grab current focused element
    var focusedElement = document.activeElement;
    // Get array of inputs
    var inputs = document.getElementsByTagName('input');
    // Set delay of 2 seconds.
    setTimeout(function() {
        // Loop through inputs
      for (i = 0; i < inputs.length; i++) {
        // If current evaluated input is one with focus...
        if (inputs[i] === document.activeElement) {
            // Grab the next index...
          var focus_input = i + 1;
          // Assure it isn't undefined.
          if (inputs[focus_input]) {
            // Give new input focus.
            inputs[focus_input].focus();
          }
        }
      }
    }, 2000)
  }
}

Good luck!