Akash Deshpande
Akash Deshpande

Reputation: 2645

In jQuery how can I get the next selector in a nested loop?

I have the following structure:

<div class="foo">
     <div class="moo">
            <div class="too"> <input type="hidden" val="56"/></div>
     </div>       
</div>
<div class="foo">
     <div class="moo">
            <div class="too">  <input type="hidden" val="58"/></div>
     </div>       
</div>

Continued...

//jQuery Code
$('.too').live('click',function(){
  var next_value = $(this).next('.too').find('input').val();
  console.log(next_value);
});

Now I want the value of the next "too" input. How can I get this? It's not working.

Upvotes: 0

Views: 129

Answers (3)

Binnng
Binnng

Reputation: 21

$('.too').live('click',function(){
  var next_value = $(this).parent('.foo').next().find('input').val();
  console.log(next_value);
});

by the way,i think you should give up .live().

Upvotes: 0

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

Your problem is that .next() traverses sibling elements. One approach would be to climb up the DOM tree, then back down. For example:

$('.foo').on('click', '.too', function () {
  var next_value = $(this).closest('.foo').next().find('input').val();
});

Also, you should try to avoid .live(). If you are using jQuery 1.7+, you'll want to use .on() (as shown in my example). If you are using anything before 1.7, try .delegate() or .bind().

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191779

First off, do not use .live. Use event delegation.

Second, .next only works with siblings. You can get the next sibling in a variety of ways -- assuming that the the .foo / .too structure is unique to the document, you can use the following:

var next_value = $(".too").eq($('.too').index(this) + 1);

Upvotes: 1

Related Questions