Search code examples
jqueryfocus

next().focus() only works for controls of same type


I'm trying to make Enter-key in forms move focus to the next control. I got several textboxes, checkboxes and buttons. They all got class='ctrl'. This code does most of the trick.

$(document).on('keydown', '.ctrl', function(e) {
    if (e.keyCode==13) {
      $(this).next().focus();
    }
})
.ctrl {
  display:block 
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="ctrl" type="text" id="fname" name="fname">
<input class="ctrl" type="text" id="mname" name="mname">
<input class="ctrl" type="text" id="lname" name="lname"><br>
<input class="ctrl" id="check1" type="checkbox">Select 1
<input class="ctrl" id="check2" type="checkbox">Select 2
<input class="ctrl" id="check3" type="checkbox">Select 3
<button type="button" class="ctrl" ;">Done</button>

But if a textbox got the focus, it only jumps to other textboxes. If a checkbox got the forcus, it only jump to other checkboxes and so on. I would like et to behave as the TAB-key.


Solution

  • You can get index of class where keypress event has taken place then add 1 to it to get next index of same class then use $(this).closest('div').find('.ctrl:eq(' + index + ')') to focus next inputs.

    Demo Code :

    $(document).on('keydown', '.ctrl', function(e) {
      var length = $(".ctrl").length //get length
      var index = $(".ctrl").index(this) + 1; //get index of class
      if (e.keyCode == 13) {
      //if index is less
        if (index < length) {
          //get closest div find class with same index
          $(this).closest('div').find('.ctrl:eq(' + index + ')').focus();
        } else {
        //focus first input
        $(this).closest('div').find('.ctrl:eq(0)').focus();
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <input class="ctrl" type="text" id="fname" name="fname">
      <input class="ctrl" type="text" id="mname" name="mname">
      <input class="ctrl" type="text" id="lname" name="lname"><br>
      <input class="ctrl" id="check1" type="checkbox">Select 1
      <input class="ctrl" id="check2" type="checkbox">Select 2
      <input class="ctrl" id="check3" type="checkbox">Select 3
      <button type="button" class="ctrl">Done</button>
    </div>