Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find "next" form input element in jQuery?

People also ask

What is next() in jQuery?

The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

What is $$ in jQuery?

$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.


kudos,

What about using .index?

e.g $(':input:eq(' + ($(':input').index(this) + 1) + ')');


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...


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):

<script>
  $(function() {
    $('a[href], button, input, select, textarea').click(function() {
      console.log(nextOnTabIndex($(this)).attr('name'));
    })
  });
</script>

<form>
  <input type='text' name='a'/>
  <input type='text' name='b' tabindex='1' />
  <a>Hello</a>
  <input type='text' name='c'/>
  <textarea name='d' tabindex='2'></textarea>
  <input id='submit' type='submit' name='e' tabindex='1' />
</form>

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.


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:

<div>
    <input id="FormElement_0" type="text" />
    <input id="FormElement_1" type="text" />
<div>

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.


You can do this to take a complete list of the form elements you are looking for:

var yourFormFields = $("yourForm").find('button,input,textarea,select');

Then, should be easy find the next element:

var index = yourFormFields.index( this ); // the index of your current element in the list. if the current element is not in the list, index = -1

if ( index > -1 && ( index + 1 ) < yourFormFields.length ) { 

                    var nextElement = yourFormFields.eq( index + 1 );

                    }