Best way to find “next” form input element in jQuery?

前端 未结 12 1523
滥情空心
滥情空心 2020-12-02 18:18

Using jQuery, what\'s the best way to find the next form element on the page, starting from an arbitrary element? When I say form element I mean ,

相关标签:
12条回答
  • 2020-12-02 18:52

    redsquare is absolutely right, and a great solution also, which I also used in one of my project.

    I just wanted to point out that he is missing some parentheses, since the current solution concatenates the index with 1, instead of adding them together.

    So the corrected solution would look like:

    $(":input:eq(" + ($(":input").index(this) + 1) + ")");
    

    Sorry about the double-post, but I couldn't find a way to comment his post...

    0 讨论(0)
  • 2020-12-02 18:53

    You can use jQuery field plugin which allows you to do that.

    0 讨论(0)
  • 2020-12-02 18:53
    var elementSelector = "input:visible,textarea:visible";
    var nextSibling = $(elementSelector )[$(elementSelector ).index() + 1];
    //$(nextSibling).focus(); possible action
    

    I just think above solution is simpler, or you can just add it all in one line if you want :-)

    var nextSibling = $("input:visible,textarea:visible")[$("input:visible,textarea:visible").index() + 1];
    
    0 讨论(0)
  • 2020-12-02 18:56

    Or you could use the html attribute 'tabindex' which is for when a user tabs around a form, it goes to tabindex="i" to tabindex="i+1". You can use jQuery to get the attribute very easily. Would make for a nice fall back to users without javascript enabled, also.

    0 讨论(0)
  • 2020-12-02 18:59

    This worked well for me, and it correctly skips over hidden inputs:

    input_el.nextAll( 'input:visible:first' ).focus();
    
    0 讨论(0)
  • 2020-12-02 19:01

    After trying every code I could find (and having issues between browsers), I found one that works in the top browsers. Couldn't use the previous routines because of some weird issues.

    $(document.body).keydown(function(event) {
        if(event.keyCode == 13 ) {
            $(":input")[$(":input").index(document.activeElement) + 1].focus();
            return false;
        }
    });
    

    Hope this helps someone else. Enjoy.

    0 讨论(0)
提交回复
热议问题