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
?
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?
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
$(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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With