Auto focus to next TextBox when MaxLength reached in JavaScript

Last Reply 3 months ago By dharmendr

Posted 3 months ago

Hi,

I give input 4 digit, 6 digit, 6 digit in 3 fields, it works fine in chrome.

But getting problem in Internet Explorer able to insert 3,5,6 digits instead of 4,6,6 digits. 

I want to get same behavior in all browsers.

  <asp:TextBox ID="second" runat="server" size="4" maxlength="4" onkeypress="input_onchange(this)" ></asp:TextBox>
  <asp:TextBox TextMode="Password" ID="third" runat="server" size="6" maxlength="6" onkeypress="input_onchange(this)" ></asp:TextBox>
  <asp:TextBox ID="fourth" runat="server" size="6" maxlength="6" ></asp:TextBox>

 

function input_onchange(me) {
    if (me.value.length < me.getAttribute('maxlength') - 1) {
        return;
    }
    var i;
    var elements = me.form.elements;
    for (i = 0, numElements = elements.length; i < numElements; i++) {
        if (elements[i] == me) {
            break;
        }
    }
    elements[i + 1].focus();
}

Please check it, how can I do this?

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago Modified on 3 months ago

Hi Alauddin,

Refer below modified code.

HTML

<asp:TextBox ID="second" runat="server" size="4" MaxLength="4" onkeypress="input_onchange(this)"></asp:TextBox>
<asp:TextBox TextMode="Password" ID="third" runat="server" size="6" MaxLength="6"
    onkeypress="input_onchange(this)"></asp:TextBox>
<asp:TextBox ID="fourth" runat="server" size="6" MaxLength="6"></asp:TextBox>
<script type="text/javascript">
    function input_onchange(me) {
        if (me.value.length <= me.getAttribute('maxlength') - 1) {
            return;
        }
        var i;
        var elements = me.form.elements;
        for (i = 0, numElements = elements.length; i < numElements; i++) {
            if (elements[i] == me) {
                break;
            }
        }
        elements[i + 1].focus();
    }
</script>

Screenshot

IE

Chrome and Mozilla