1

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();
});
simple
  • 2,327
  • 7
  • 35
  • 55

3 Answers3

2

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.

http://jsfiddle.net/8TVxd/

$('.add').click(function(){
    $(this).next('div').find('textarea:visible:first').focus();
});
Jason P
  • 26,984
  • 3
  • 31
  • 45
1

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

JSFiddle

kunalbhat
  • 1,709
  • 10
  • 11
0

This should do it:

$(this).next().find('textarea').filter(':visible').first().focus();

jsFiddle updated

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.

Community
  • 1
  • 1
PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40