0

I'm looking to setup a standard DOB question where, once the user satisfies the maxlength requirement, it will automatically focus onto the next input (being the month field).

However, my current approach doesn't autofocus onto the next field?

$(function() {

  $(".input").keyup(function() {
    if (this.value.length == this.maxLength) {
      console.log(this.maxLength);
      var $next = $(this).next('.input');
      if ($next.length)
        $(this).next('.input').focus();
      else
        $(this).blur();
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="question question--1">
  <input class="input" type="number" data-format="day" placeholder="DD" maxlength="2" />
</div>

<div class="question question--2">
  <input class="input" type="number" data-format="month" placeholder="MM" maxlength="2" />
</div>

<div class="question question--3">
  <input class="input" type="number" data-format="year" placeholder="YYYY" maxlength="4" />
</div>

I believe the issue might be because the next .input is in another parent element. I've tried tweaking it to the following:

var $next = $(this).parent(".question").next('.input');

But still the same results.

Freddy
  • 683
  • 4
  • 35
  • 114
  • Does this answer your question https://stackoverflow.com/questions/2702862/jquery-check-length-of-input-field? – Grumpy Sep 04 '21 at 19:00
  • Here you'll find the answer with JQ and Vanilla JS also: https://stackoverflow.com/questions/15595652/focus-next-input-once-reaching-maxlength-value – 1x2x3x4x Sep 04 '21 at 19:01
  • @Grumpy - Nope, I think it's the issue I am having is because my `inputs` are children of different parent `divs`. Existing questions on SO show all inputs under the same parent / level – Freddy Sep 04 '21 at 20:18

1 Answers1

0

Check for $next = $(this).parent('div').next('div').find('.input'); length and focus on that .input using $next not with $(this).next('.input').

Example:

$(function() {
  $(".input").keyup(function() {
    if (this.value.length == this.maxLength) {
      var $next = $(this).parent('div').next('div').find('.input');
      if ($next.length) {
        $next.focus();
      } else {
        $(this).blur();
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="question question--1">
  <input class="input" type="number" data-format="day" placeholder="DD" maxlength="2" />
</div>

<div class="question question--2">
  <input class="input" type="number" data-format="month" placeholder="MM" maxlength="2" />
</div>

<div class="question question--3">
  <input class="input" type="number" data-format="year" placeholder="YYYY" maxlength="4" />
</div>
4b0
  • 21,981
  • 30
  • 95
  • 142