1

I have this code:

<c:forEach items="${ sample }" var="test">
    <tr>
        <td><strong>${ test.test }.</strong></td> // I want to get the text
        <td>
            <fieldset class="span11">
                <div class="control-group">
                    <label class="control-label"><strong>${ test.blah }</strong></label>
                    <div class="controls" id="question${ test.blah }">
                        <c:forEach var="beng" items="${ anotherSample }">
                            <form:radiobutton path="boom" class="question-choices" data-label="${ choices }" value="${ beng-boom }"/><br>
                        </c:forEach>
                    </div>
                </div>
            </fieldset>                 
        </td>
    </tr>
</c:forEach>

I want to get the text from the first <td> from the radio button:

What I tried so far is:

$('.question-choices').on('change', function() {
    console.log( $(this).parent('tr').closest('td').text() );
});

But this returns empty string

4
  • 2
    Because the parent is a div, not a tr. Read the docs for more information. api.jquery.com/parent Commented Nov 25, 2013 at 14:42
  • @epascarello parents('tr') seems to do what OP wants. Could be a typo. Commented Nov 25, 2013 at 14:47
  • parents() is a bad choice. Commented Nov 25, 2013 at 14:51
  • @epascarello is there a reason to that? Commented Nov 25, 2013 at 14:52

2 Answers 2

2

try this;

$('.question-choices').on('change', function() {
    console.log( $(this).closest('tr').find('td:first').find("strong").html() );
});
Sign up to request clarification or add additional context in comments.

3 Comments

I want the readability of this but this also includes the <strong> tag
Is there a reason why did you use .find("strong").html() instead of .text()?
I prefer to use html() in this case to get all content @newbie
1

parent() only gets a direct parent.

Try using .parents:

$('.question-choices').on('change', function() {
    console.log( $(this).parents('tr').closest('td').text() );
});

1 Comment

parents() would give you multiple elements if nested tables. This is also broken because .closest('td') would be looking at the TR's parents!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.