automatically tab to the next input field in cells of a table

I want to automatically tab to the next input field when reaching the maxlength of each field. Each input field is placed in a cell of a table.

<table border="0" cellpadding="1" cellspacing="1" class="td1202">
<tbody>
        <tr>
        <td>&nbsp;</td>
        <td><input maxlength="1" type="text" style="width: 20px;"></td>
        <td><input maxlength="1" type="text" style="width: 20px;"></td>
        <td class="decimal">,</td>
        <td><input maxlength="1" type="text" style="width: 20px;"></td>
        <td><input maxlength="1" type="text" style="width: 20px;"></td>
        <td><input maxlength="1" type="text" style="width: 20px;"></td>
    </tr>
</tbody>

I've tried this so far:

$("input").keyup(function() {
 if (this.value.length == this.maxLength) {
$(this)
  .blur()
  .parent()
  .next()
  .children('input')
  .focus();
}
});

Upvotes: 1

Views: 883

Answers (1)

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21756

Explanation:

Your code was not working because you have <td class="decimal">,</td> and due to which your code is not able to find the next input children so it stops working after first two inputs. Your code will work if <td class="decimal">,</td> is not there.

Solution:

Instead of checking child etc you can you can simply find the index of next input.

Below is working example:

$("input").keyup(function() {
  if (this.value.length == this.maxLength) {
    var index = $(this).index("input");
    $("input:eq(" + (index + 1) + ")").focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0" cellpadding="1" cellspacing="1" class="td1202">
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td><input maxlength="1" type="text" style="width: 20px;"></td>
      <td><input maxlength="1" type="text" style="width: 20px;"></td>
      <td class="decimal">,</td>
      <td><input maxlength="1" type="text" style="width: 20px;"></td>
      <td><input maxlength="1" type="text" style="width: 20px;"></td>
      <td><input maxlength="1" type="text" style="width: 20px;"></td>
    </tr>
  </tbody>

Upvotes: 4

Related Questions