focus on next tabindex of HTML element onEnter keypress by JQuery

后端 未结 6 1675
日久生厌
日久生厌 2020-12-05 11:06

Hi Friends, I\'m working on a small task which is to enable the user to tabindex the html element upon enter keypress.

As im new to jquery , I have

6条回答
  •  清歌不尽
    2020-12-05 11:43

    Didn't want to make new post and make SPAM with solution I found useful.

    Collected information from other sources (Brian Glaz code nice-one) and made cross-browser version of Focus Next Element In Tab-index using Enter key.

    Tab-indexes are not one after another, but may also contain a space between (1,2,9,11,30,etc.)

    var tabindex = 1; //start tabindex || 150 is last tabindex
        $(document).keypress(function(event) {
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if(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");
        })
    

    I hope that someone will find it useful. Feel free to edit/comment it.

提交回复
热议问题