Javascript tabindex focus sets focus to next element

2.9k Views Asked by At

In the below sample, I am trying to have the navigation within the div. Used a JS function to get the current element and check and set the focus. But it sets the focus to next element always. Can somebody check?

function loadOverlay(event) {
  var oly = document.getElementById('overlay');

  oly.style.display = "block";
  document.getElementById('userName').focus();


}
// restore page to normal
function restore() {

  // document.body.removeChild(document.getElementById("overlay"));
  //document.getElementById('overlay').focus();
}

// restore page to normal
function sayHi() {
  alert("Hi");
}

function navigate(event, maxtab) {
  //alert(event); 
  if (window.event) {
    caller = window.event.srcElement; //Get the event caller in IE.
    key = window.event.keyCode; //Get the keycode in IE.
  } else {
    caller = event.target; //Get the event caller in Firefox.
    key = event.which; //Get the keycode in Firefox.
  }

  var currtab = document.activeElement.tabIndex;
  // alert(key);
  if (key == 9) {
    if (currtab == 6) {
      document.getElementById("userName").focus();

    }
  }

}
#outer {
  width: 100%;
  height: 100%;
}

.overlay {
  background-color: grey;
  opacity: .7;
  filter: alpha(opacity=70);
  position: fixed;
  top: 100px;
  left: 100px;
  width: 500px;
  height: 300px;
  z-index: 10;
  border: 1px solid black;
  display: none;
}
<div id="outer">
  <p>Check overlay</p>
  <input type=button onclick="loadOverlay(event)" value="Open overlay">
</div>

<div id="overlay" class="overlay" onkeydown="navigate(event, 5)">
  <h1>Enter your Name and Pasword </h1><br>
  <table border=1>
    <tr>
      <td>Enter Your Name :</td>
      <td>
        <input tabindex="2" type="text" id="userName" value=""></td>
    </tr>
    <tr>
      <td>Enter Your PassWord :</td>
      <td><input tabindex="3" type="password" id="userPassWord" value=""></td>
    </tr>
    <tr>
      <td>Confirm Your PassWord :</td>
      <td><input tabindex="4" type="password" id="userRePassWord" value=""></td>
    </tr>
    <tr>
      <td align=center><input tabindex="5" type="submit" id="formsub" name="Submit" value="Submit"></td>
      <td align=center><input tabindex="6" type="reset" id="formref" name="reset" value="Refresh"></td>
    </tr>
  </table>
</div>

0

There are 0 best solutions below