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

前端 未结 12 1585
滥情空心
滥情空心 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 19:15

    This solution does not require indexes, and also plays nicely with tabindex - in other words, it gives you the exact element that the browser would give you on tab, every time, without any extra work.

    function nextOnTabIndex(element) {
          var fields = $($('form')
                        .find('a[href], button, input, select, textarea')
                        .filter(':visible').filter('a, :enabled')
                        .toArray()
                        .sort(function(a, b) {
                          return ((a.tabIndex > 0) ? a.tabIndex : 1000) - ((b.tabIndex > 0) ? b.tabIndex : 1000);
                        }));
    
    
          return fields.eq((fields.index(element) + 1) % fields.length);
        }
    

    It works by grabbing all tabbable fields in the form (as allowed by http://www.w3.org/TR/html5/editing.html#focus-management), and then sorting the fields based on (http://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute) to work out the next element to tab to. Once it has that, it looks at where the passed in field is in that array, and returns the next element.

    A few things to note:

    • jQuery appears to support sort() on a jQuery object, but I can't find it explicitly in the documentation, hence calling toArray() and then rewrapping the array in a jQuery object.
    • There are other fields that it is okay to tab to, but I left them out as they aren't standard form fields.

    The code I used to test this was (using jQuery 1.7):

    
    
    
    Hello

提交回复
热议问题