Search code examples
javascripthtmltabindex

Checkbox tabindex unexpected behavior


I'm using this javascript to automatically jump to the next field:

    <script>
    function checkLen(x,y)
    {
    if (y.length==x.maxLength)
      {
      var next=x.tabIndex;
      if (next<document.getElementById("formid").length)
        {
        document.getElementById("formid").elements[next].focus();
        }
      }
    }
    </script>

and this is my form:

<form action="random.php" id="formid" method="post">
   <input type="checkbox" name="cbox" tabindex="4" />Default
   <input type="text" name="text1" id="text1" tabindex="1" />
   <input type="text" name="text2" id="text2" tabindex="2" maxlength="1" onkeyup="checkLen(this,this.value)" />
   <input type="text" name="text3" id="text3" tabindex="3" />
</form>

What happens is that when I finish typing in text2 a single character (maxlength="1"), it jumps to the checkbox which has a tabindex of 4, whereas it is, logically, meant to jump to text3 which has a tabindex of 3.

I've done all kinds of stuff, like remove tabindex from the checkbox, give it the last tabindex order, but it's not working.

I want my caret to jump, on typing of a single character, from text2 to text3.


Solution

  • Because of the ordering of your inputs, the tabindex of text2 actually corresponds to its zero-based ordinal position (2) within the elements collection, causing you to focus text2. You'll need to add 1 to next in order to select text3 within the elements collection.