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

前端 未结 12 1582
滥情空心
滥情空心 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:09

    You could give each form item an id (or unique class name) that identified it as a form element and also gave it an index. For example:

    Then, if you want to traverse from the first element to the second you can do something like this:

    //I'm assuming "this" is referring to the first input
    
    //grab the id
    var id = $(this).attr('id');
    
    //get the index from the id and increment it
    var index = parseInt(id.split('_')[0], 10);
    index++;
    
    //grab the element witht that index
    var next = $('#FormElement_' + index);
    

    The benefit of this is that you can tag any element to be next, regardless of location or type. You can also control the order of your traversal. So, if for any reason you want to skip an element and come back to it later, you can do that too.

提交回复
热议问题