Auto tab text form fields with jQuery

Problem

Need to auto tab to the next form field when the maximum number of entered characters is reached.

Solution

Assigned [maxlenght] attribute and [autotab] class to each field you want to auto tab. Add the following code to $(document).ready event:

$('.autotab').keydown(function(event) {
    //save previously entered value prior to keyup event
    $(this).attr('prevValue', $(this).val());
});

$('.autotab').keyup(function(event) {
    var newValue = $(this).val();
    //see if the textbox had its value changed
    if ($(this).attr('prevValue') != newValue) {
        //see if the number of entered characters is equal or greater
        //than the allowable maxlength
        if (newValue.length >= $(this).attr('maxlength')) {
            //set focus on the next field with autotab class
            $(this).next('.autotab').focus();
        }
        //save newly entered value for the next execution of this event
        $(this).attr('prevValue', newValue)
    }
});

Hopefully, my comments in the above code is enough to understand how it works.

2 thoughts on “Auto tab text form fields with jQuery”

    1. I know this was posted quite a while ago, but I wanted to let you know this really helped me out! I had been trying to do this on my own and was struggling with a workaround for the problem of going back to a “complete” field and having it autotab instantly… your “prevValue/newValue” logic was exactly what I was missing!

Leave a Reply

Your email address will not be published. Required fields are marked *