2

Starting from a particular div I want to use jquery to grab the value of the input tag in the next div block (two levels down). I have an HTML structure like this:

<div class="firstClass1" id="firstID1"> // suppose I start from this element
    <div class="secondClass1" id="secondID1">
        <input value="myValue1"/>
    </div>
</div>
<div class="firstClass2" id="firstID2">
    <div class="secondClass2" id="secondID2">
        <input value="myValue2"/>
    </div>
</div>
<div class="firstClass3" id="firstID3">
    <div class="secondClass3" id="secondID3">
        <input value="myValue3"/>
    </div>
</div>
...

That is, if I start from .firstClass1, I want to get the value from myValue2. I have tried using the following jquery, but it doesn't work:

var nextID = $('.div#firstID1').next().find('input').val();

and

var nextID = $('.div#firstID1').next().next().val();
Jonas
  • 121,568
  • 97
  • 310
  • 388
Ajay Mohite
  • 119
  • 3
  • 13

4 Answers4

3

This will help : http://jsfiddle.net/bQYZJ/

You had extra . dot as well as id was firstID1 not firstID :) Rest I have tuned it for your need.

Hope this help,

code

var nextID = $('div#firstID1').next('div').find('input').val();
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1

you have missed a quotation mark, also remove the dot from .div#firstID1:

var nextID = $('div#firstID').next().find('input').val();
Ram
  • 143,282
  • 16
  • 168
  • 197
1

Replace the .div with just div.

Just try with:

$('div[id^=firstID]').mouseenter(function(){
    var nextID = $(this).next().find('input').prop('value');
    alert( nextID ); // test it!
});

$('div[id^=firstID]') means "any div which ID starts with firstID",
this will allow you to grab the 'next div input value' of any 'evented' element so you don't need to rewrite the code for ANY firstID[N] element.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

You can also use,

var nextID = $('div#firstID1 > div > input')

or

var nextID = $('div#firstID1').children().children()

or

var nextID = $('div#firstID1').children('div').children('input');

But (for reasons unknown to me), find works faster than children and > approach.

Jashwant
  • 28,410
  • 16
  • 70
  • 105
  • Yeah it is weird that `find` is faster than `children`. Check out [this answer](http://stackoverflow.com/a/7692401/145346) with some interesting observations. – Mottie Jul 08 '12 at 22:49