BlackVikingPro BlackVikingPro - 2 months ago 15
Javascript Question

JavaScript Input Focus Switching

I have the below code being used in a new web app of mine, though I can't seem to get it to work like it should.. I want to be able to load up the page, then if the client hits the "Tab" key then it will simply just focus to the other input field. There being only 2 input fields, this should be easy (at least I thought :P). Anyways, can anybody help me with this? Thanks in advance :)

var body = document.querySelector('body');

body.onkeydown = function (e) {
if ( !e.metaKey ) {
// e.preventDefault();
}
if (e.code == "Tab") {
console.log(e.code);
if ($('#username').is(":focus")) {
$('#password').focus();
} else if ($('#password').is(":focus")) {
$('#username').focus();
}
}
}

Answer

I'm assuming you're using JQuery since you use $ in your javascript so I wrote this example under that assumption. I'm assuming you want it to tab into the field regardless so if they press the tabkey, it defaults to the id="username" input element. I added in a preventDefault to stop the normal tab behavior. It seems that the tabs normal behavior is what causes it to not function properly. Hope I didn't misunderstand you and that this helps.

$("body").on("keydown", function(e) {
  if (e.which !== 9 && e.keyCode !== 9) {
    return;
  }
  console.log("Which Value:", e.which);
    console.log("KeyCode Value:", e.keyCode)

  e.preventDefault();
  if (!$('#username').is(":focus")) {
    $('#username').focus();
  } else {
    $('#password').focus();
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <input id="username">
  <input id="password">
</body>

EDIT:

In case you wanted to do this without the JQuery selectors. Here's another example:

var body = document.getElementsByTagName("body");

body[0].onkeydown = function(e) {
  var username = document.getElementById("username");
  var password = document.getElementById("password");
  if (e.which !== 9 && e.keyCode !== 9 && e.code !== "Tab") {
    return;
  }
  e.preventDefault();
  if (document.activeElement !== username) {
    username.focus();
  } else {
    password.focus();
  }
}
<body>
  <input id="username">
  <input id="password">
</body>