Jquery .next(input OR textarea)

sscirrus picture sscirrus · Oct 8, 2011 · Viewed 11.5k times · Source

I'm messing with this simple line of code:

$(this).next('input').focus();

I'd like to get it to select the next (input OR textarea), whichever comes first - how can I do this?

As an alternative, how can I get it to simply focus on the next item in the tabindex?

Edit

Because the next input/tabindex is not always right after $(this), how can I easily traverse down the list of siblings until I find the next match?

Answer

Gabe picture Gabe · Oct 8, 2011

Use :input which selects all input, textarea, select and button elements.

$(this).next(':input').focus();

jsFiddle

If the next input is not a sibling, this seems to work... For this example, click in the textbox with the id="test" and it will focus on the next :input element.

<input type="text" value="hello world2"/>
<input type="text" value="hello world3"/>
<div>
    <input type="text" id="test"/>
</div>
<div>
    <div>Hi</div>
</div>
<textarea>found me</textarea>
<input type="text" value="hello world"/>

$(document).ready(function(){
    $('#test').click(function(){
       var c = $(this).parents().nextAll(':input:first').focus();
    });
});

jsFiddle2