Search code examples
javascriptjqueryhtmlkeydownpreventdefault

HTML textboxes are not working


I want to redirect from current to nextpage on F1 button click. The page redirects properly, but the textboxes of the current page are not working.

$(document).ready(function () {
    $("body").keydown(function (e) {
        e.preventDefault();
        if (event.keyCode === 112) {
            window.location.href = "../nextpage.aspx";
        }
    });
});

What should I do to resolve the issue?


Solution

  • Currently your "preventDefault()" fires in all circumstances, stopping the other keys from working properly. You really only need to do that if you detect that the key is F1 specifically:

    Demo of non-working code:

    Note that it's not possible to type anything into the textbox because every key's default behaviour is suppressed.

    $(document).ready(function() {
      $("body").keydown(function(e) {
        e.preventDefault();
        if (e.keyCode === 112) {
          window.location.href = "../nextpage.aspx";
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" />

    Fixed version:

    I simply move the preventDefault() inside the if statement which detects the exact key pressed.

    $(document).ready(function() {
      $("body").keydown(function(e) {
        if (e.keyCode === 112) {
          e.preventDefault();
          window.location.href = "../nextpage.aspx";
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text"/>

    P.S. I also fixed the e / event mixup in your if statement.