-2

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?

ADyson
  • 57,178
  • 14
  • 51
  • 63
CodingFriend
  • 149
  • 1
  • 12

4 Answers4

10

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.

ADyson
  • 57,178
  • 14
  • 51
  • 63
2

change if (e.keyCode === 112) instead of if (event.keyCode === 112)

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
2

e.preventDefault(); is preventing all keypresses in your page.
simply change your code like this:

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

Problem:

You define event as e but use it as event

Code :

$(document).ready(function () {
        $("body").keydown(function (e) {
            if (e.keyCode === 112) { // error was here
                e.preventDefault(); // should be inside if statement
                window.location.href = "../nextpage.aspx";
            }
   });
});

Updated code (a lil better) :

$(document).ready( () => $("body").keydown((e) => e.keyCode == 112&&(e.preventDefault(),(window.location.href= "../nextpage.aspx"))));
Muhammad Salman
  • 433
  • 6
  • 18