Jquery select NEXT text field on Enter Key Press

后端 未结 6 1458
感动是毒
感动是毒 2020-12-31 15:31

I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.



        
6条回答
  •  一个人的身影
    2020-12-31 15:54

    Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.

    I've left in my debugging code:

    try {
        var inputs = $("input[id^=tpVal-]");
        var sortedInputs = _.sortBy(inputs, function(element){
            var tabIndex = $(element).attr('tabindex');//debugging
            var id = $(element).attr('id');//debugging
            console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
            return parseInt($(element).attr('tabindex'));
        });
        $(sortedInputs).each(function (index, element) {
            $(element).keyup(function(event){
                if(event.keyCode==13) {
                    var $thisElement = $(element);//debugging
                    var nextIndex = index+1;//debugging
                    var $nextElement = $(sortedInputs[nextIndex]);
                    var thisId = $thisElement.attr('id');//debugging
                    var nextId = $nextElement.attr('id');//debugging
                    console.log("Advance from "+thisId+" to "+nextId);//debugging
                    if($nextElement!=undefined) {
                        $(sortedInputs[index + 1]).focus();
                    }
                }
            });
        });
    } catch (e) {
        console.log(e);
    }
    

提交回复
热议问题