Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .next(input OR textarea)

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?

like image 903
sscirrus Avatar asked Oct 08 '11 21:10

sscirrus


2 Answers

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

like image 171
Gabe Avatar answered Nov 10 '22 21:11

Gabe


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

But it will only work if the next input/textarea is the sibling immediately following this.

Alternatively, you can use the :focusable selector from jQuery UI.

Sample fiddle - press enter to focus the next input

You can also target the first input if no inputs are currently selected by binding to the document itself and using e.target.

like image 26
mpen Avatar answered Nov 10 '22 23:11

mpen