simple
simple

Reputation: 2397

Focus on next form element directly after button

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

Answers (3)

kunalbhat
kunalbhat

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

JSFiddle

Upvotes: 1

PlantTheIdea
PlantTheIdea

Reputation: 16359

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.

Upvotes: 0

Jason P
Jason P

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.

http://jsfiddle.net/8TVxd/

$('.add').click(function(){
    $(this).next('div').find('textarea:visible:first').focus();
});

Upvotes: 2

Related Questions