Search code examples
jqueryjquery-selectorsfocus

Focus on next input of selected class even if on another class input with jQuery


I'm having trouble finding the right code to do this in jQuery. I can focus on the next input with the '.first' class with this code. But if i'm not on a '.first' input it'll go to the first '.first' input.

This is the code snippet:

 var $first_elements = $('.section .first');
    var $inputs = $('input');
    $inputs.on('keyup', function(e) {
        if (e.which === 13) {
            var ind = $first_elements.index(this);
            $first_elements.eq(ind + 1).focus()
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <div class="section">
    <input class="first" name="input_1" /><input name="input_2" /><input name="input_3" />
    <br/>
    <input class="first" name="input_4" /><input name="input_5" /><input name="input_6" />
    <br/>
    <input class="first" name="input_7" /><input name="input_8" /><input name="input_9" />
  </div>

How can I go to the next input with the .first selector from any input?


Solution

  • Update your code like this, bind keyup event only for the input element which have class first

     var $inputs = $('input');
     $inputs.on('keyup', function(e) {
       if (e.which === 13) {
         $inputs.next('input.first').focus()
       }
     });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input class="first" name="input_1" />
    <input name="input_2" />
    <input name="input_3" />
    <input class="first" name="input_4" />
    <input name="input_5" />
    <input name="input_6" />