views:

7000

answers:

7

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 <input>, <select>, <button> or <textarea>.

In the following examples, the element with the id "this" is the arbitrary starting point, and the element with the id "next" is the one I want to find. The same answer should work for all examples.

Example 1:

<ul>
 <li><input type="text" /></li>
 <li><input id="this" type="text" /></li>
</ul>

<ul>
 <li><input id="next" type="text" /></li>
</ul>

<button></button>

Example 2:

<ul>
 <li><input id="this" type="text" /></li>
</ul>

<button id="next"></button>

Example 3:

<input id="this" type="text" />
<input id="next" type="text" />

Example 4:

<div>
  <input id="this" type="text" />
  <input type="hidden" />
  <div>
    <table>
      <tr><td></td><td><input id="next" type="text" /></td></tr>
    </table>
  </div>
  <button></button>
</div>

EDIT: The two answers provided so far both require writing a sequence number to all input elements on the page. As I mentioned in the comments of one of them, this is kind of what I'm already doing and I would much prefer have a read-only solution since this will be happening inside a plugin.

+2  A: 

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.

jckeyes
Thanks for the reply. This is unfortunately exactly what I'm trying to get rid of :) I'm moving my code into a plugin and I'd rather it was usable without clobbering the user's own choice of id's. The unique class name is interesting but I'd prefer a more "read-only" solution if possible.
Understandable. I realize the solution I provided was a bit "dirty." Makes a lot less sense from a plugin standpoint.
jckeyes
A: 

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.

Chris Serra
+7  A: 

kudos,

What about using .index?

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

redsquare
This works great. Thanks to redsquare, bobbytek4 and grault on freenode #jquery for their help.
A: 

I came up with a function that does the job without explicitly defining indexes:

function nextInput(form, id) {
    var aInputs = $('#' + form).find(':input[type!=hidden]');
    for (var i in aInputs) {
     if ($(aInputs[i]).attr('id') == id) {
      if (typeof(aInputs[parseInt(i) + 1]) != 'undefined') {
       return aInputs[parseInt(i) + 1];
      }
     }
    }
}

And here's a working example. The form tags are for consistency. All you really need is a common parent and could even just use the body tag as the parent (with a slight modification to the function).

Paste this into a file and open with firefox / firebug and you'll see it returns the correct element for all your examples:

<html>
  <head>
    <script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
    <script>
      function nextInput(form, id) {
        var aInputs = $('#' + form).find(':input[type!=hidden]');
        for (var i in aInputs) {
          if ($(aInputs[i]).attr('id') == id) {
            if (typeof(aInputs[parseInt(i) + 1]) != 'undefined') {
              return aInputs[parseInt(i) + 1];
            }
          }
        }
      }

      google.load("jquery", "1.2.6");
      google.setOnLoadCallback(function() {
        console.log(nextInput('myform1', 'this1'));
        console.log(nextInput('myform2', 'this2'));
        console.log(nextInput('myform3', 'this3'));
        console.log(nextInput('myform4', 'this4'));
      });
    </script>
  </head>
  <body>
    <form id="myform1">
      <ul>
         <li><input type="text" /></li>
         <li><input id="this1" type="text" /></li>
      </ul>
      <ul>
        <li><input id="next1" type="text" /></li>
      </ul>
    </form>

    <form id="myform2">
      <ul>
         <li><input type="text" /></li>
         <li><input id="this2" type="text" /></li>
      </ul>
      <ul>
        <li><input id="next2" type="text" /></li>
      </ul>
    </form>

    <form id="myform3">
      <input id="this3" type="text" />
      <input id="next3" type="text" />
    </form>

    <form id="myform4">
      <div>
        <input id="this4" type="text" />
        <input type="hidden" />
        <div>
        <table>
          <tr><td></td><td><input id="next4" type="text" /></td></tr>
        </table>
        </div>
        <button></button>
      </div>
    </form>
  </body>
</html>
enobrev
A: 

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

                    }
alexmeia
A: 

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

HappyCoder
A: 

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

reSPAWNed