Set Focus to the Next Input Field with jQuery

Setting focus to input fields is easy enough with JavaScript: document.getElementById(‘theInputField’).focus(); but sometimes you need a more generic solution as what happens when the next input field changes ID?

There are some options to do it, we want to show you some of them:

  1. I was recently faced with the problem of setting focus to the next input field. The challenge was that I didn’t know what that field was. So given an input field, find the next logical (in the order of the DOM) input field and set focus. I came up with the following jQuery function (plugin) to accomplish this:
    $.fn.focusNextInputField = function() {
        return this.each(function() {
            var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
            var index = fields.index( this );
            if ( index > -1 && ( index + 1 ) < fields.length ) {
                fields.eq( index + 1 ).focus();
            }
            return false;
        });
    };
    

    Reference link: http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/

  2. Another option is with tabindex attribute:
    
    var tabindex = 1; //start tabindex || 150 is last tabindex
    $(document).keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '9' || keycode == '13') { //onEnter
    tabindex++;
    //while element exist or it's readonly and tabindex not reached max do
    while(($("[TabIndex='"+tabindex+"']").length == 0 || $("[TabIndex='"+tabindex+"']:not([readonly])").length == 0) && tabindex != 150 ){
    tabindex++;
    }
    if(tabindex == 150){ tabindex = 1 } //reseting tabindex if finished
    $("[TabIndex='"+tabindex+"']").focus()
    return false;
    }
    });
    
    $("input").click(function() { //if changing field manualy with click - reset tabindex
    var input = $(this);
    tabindex = input.attr("tabindex");
    });
  3. Another option:
    $("input,select").bind("keydown", function (e) {
    if (e.keyCode == 13) {
    var allInputs = $("input,select");
    for (var i = 0; i < allInputs.length; i++) {
    if (allInputs[i] == this) {
    while ((allInputs[i]).name == (allInputs[i + 1]).name) {
    i++;
    }
    
    if ((i + 1) < allInputs.length){
    $(allInputs[i + 1]).focus();
    }
    }
    }
    }
  4. How to catch enter key and change event to tab
    $('input').keydown( function(e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            if(key == 13) {
                e.preventDefault();
                var inputs = $(this).closest('form').find(':input:visible');
                inputs.eq( inputs.index(this)+ 1 ).focus();
            }
        });

Leave a comment