tonyf tonyf - 5 months ago 14
Javascript Question

Get an Element's td Value below an input tag using jQuery

I have the following sample HTML code:

<tr>
<td align="center" headers=" " class="data"><input type="checkbox" name="the-id" value="4222816"></td>
<td headers="HDR1" class="data">RED</td>
<td headers="HDR2" class="data">YELLOW</td>
</tr>


Based on the above, with jQuery, I want to be able to advance to the next td element from input inorder to obtain the value "RED"

I believe it should be something like:

$("input[value="4222816"]").closest('td')


But unsure how to get to the td value of "RED"

Any help would be great.

Answer

closest is for ancestor elements. You're looking for parent().next(): parent to go up to the td containing the input, then next to go to the next element after it:

var text = $('input[value="4222816"]')
              .parent()
              .next()
              .text();

However: If you have more than one element that matches input[value="4222816"], because of the set-based nature of jQuery, that will give you the text of all of them. (text is unusual in the jQuery world in this regard. The vast majority of jQuery's accessors would only give you the value from the first element in the set, but text gives you the value from all elements in the set.)

So if you have multiple matching elements, you'll need to narrow the selector or otherwise winnow it down to just one element.

Here's an example that uses the first matching element via .first; but you wouldn't need that if there were only one match:

$("#result").text(
  $('input[value="4222816"]')
    .first()
    .parent()
    .next()
    .text()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td align="center" headers=" " class="data">
        <input type="checkbox" name="the-id" value="4222816">
      </td>
      <td headers="HDR1" class="data">RED</td>
      <td headers="HDR2" class="data">YELLOW</td>
    </tr>
    <tr>
      <td align="center" headers=" " class="data">
        <input type="checkbox" name="the-id" value="4222816">
      </td>
      <td headers="HDR1" class="data">BLUE</td>
      <td headers="HDR2" class="data">GREEN</td>
    </tr>
  </tbody>
</table>
<p>The text of the target <code>td</code> is: <span id="result"></span></p>

If you needed to go further that the immediately-next element, it would be .nextAll("some-selector").first() rather than .next(). (Note: Don't be fooled by the fact next optionally takes a selector. It doesn't find the next matching element. It either finds the next element, if it matches, or none if it doesn't.)