Reputation: 2397
How do I focus on the next textarea that comes after the button that was clicked?
http://jsfiddle.net/infatti/GmPCz/
$('.add').click(function(){
$(this).closest('div').next('textarea:visible').focus();
});
Upvotes: 1
Views: 339
Reputation: 1719
Try finding the next div
and focusing on the first available textarea
. Also, make sure to override the default behavior of an anchor tag with preventDefault()
:
$('.add').click(function(event){
event.preventDefault();
$(this).next('div').find('textarea:visible').first().focus();
});
Upvotes: 1
Reputation: 16359
This should do it:
$(this).next().find('textarea').filter(':visible').first().focus();
The use of .filter(':visible')
and .first()
instead of including it in the selector is for performance reasons. It avoids having to do additional queries, as it merely pares down the existing result set from the initial single query.
Example explanation of the performance difference.
Upvotes: 0
Reputation: 27012
closest()
starts with the current element and searches up the DOM for the first element matching the selector. The div you want isn't an ancestor of the link, but a sibling.
$('.add').click(function(){
$(this).next('div').find('textarea:visible:first').focus();
});
Upvotes: 2