How to move focus on next field when enter is pressed?

后端 未结 7 912
我在风中等你
我在风中等你 2020-12-29 06:02

Can you please tell me how to move focus on to the next field when the enter key is press? I use the dform plugin (which converts JSON to a form).

I Go

7条回答
  •  感情败类
    2020-12-29 06:22

    The following code should do it; it uses the tabIndex property. Let us know if that's is not acceptable:

    $(function() {
        $('input').on('keypress', function(e) {
            e.which !== 13 || $('[tabIndex=' + (+this.tabIndex + 1) + ']')[0].focus();
        });
    });
    

    The drop down already has enter key slated for opening the drop down.

    JS FIDDLE DEMO

    To be able to do something before moving to the next form element, you can use the following version:

    $(function() {
        $(document).on('keypress', function(e) {
            var that = document.activeElement;
            if( e.which == 13 ) {
                e.preventDefault();
                alert( "dd" );
                $('[tabIndex=' + (+that.tabIndex + 1) + ']')[0].focus();
            }            
        });
    });
    

    DEMO

提交回复
热议问题