Search code examples
jqueryasp.nettabsphone-number

Automatically advance to next field in HTML form without changing tab behaviour


I have five textboxes in same order as mentioned below with IDs

  1. txtFirstName
  2. txtLastName
  3. txtEmailAddress
  4. txtTelcode
  5. txtTelephoneNumber

I want tab functionality for phone numbers (txtTelcode and txtTelephoneNumber).

Maxlength of textbox txtTelcode is 5. Below is the functionality required.

When user fill txtTelcode, then after entering 5 digits tab should be automatically shifted to next textbox txtTelephoneNumber.

I used the below code which is working fine but I am facing one issue.

$(document).ready(function () {
    $('#' + telcode).keyup(function () {
        if ($.trim($('#' + telcode).val()).length == "5") {
            $('#' + txtTelephoneNumber).focus();
        }
    });
});

The problem is that if there are already 5 digits in txtTelcode then when the user tabs into txtTelcode this function automatically advances them to txtTelephoneNumber without stopping in txtTelcode. This is not what I want to happen; instead I need to be able to tab into txtTelcode even when it is complete. How can I modify my code to fix this, or how else can I implement this?


Solution

  • I modified my own code as mentioned below. I prevented my code to run if Tab is pressed by getting e.keyCode.

    For shift + tab functionality I prevented my code to run if Shift is pressed by getting e.keyCode.

    $('#' + telcode).keyup(function (e) {
                if (e.keyCode != 16) {
                    if (e.keyCode != 9) {
                        if ($.trim($('#' + telcode).val()).length == "5") {
                            $('#' + txtTelephoneNumber).focus();
                        }
                    }
                }
            });
    

    This code is working fine.