Search code examples
javascriptjquerydebuggingkeypress

jQuery keypress binding works only when a breakpoint is set in Visual Studio debugger


I think there must be a race condition but don't know how to fix it.

I've got several INPUTs lined up in row, each having a maxlength =1, and I want to move through them as the user types an alphabetic letter:

      /* jQuery 3.6.0 */
      $("input").bind("keypress", function (e) {
            if (/[A-Z]/i.test(e.key)) {
              /* breakpoint on this next line */
                $(this).next('input').focus();  
            }
        });

If I put a breakpoint on the line as indicated, the debugger stops there as expected, and if I press [F5] to continue, focus is indeed advanced to the next INPUT. But if I remove the breakpoint, and run the program normally, the focus does not advance.


Solution

  • Problem you have is you have a race condition of the action of the event and the focus. You can get around it with a timeout

    $("input").bind("keypress", function(e) {
      if (/[A-Z]/i.test(e.key)) {
        window.setTimeout(() => $(this).next('input').focus(), 0);
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <input type="text" />