1

I have the following html code in my application:

<tr style="cursor:pointer;">
    <td>100101</td>
    <td>Monkey</td>
    <td>Nuts<td>
    <td>Cow</td>
    <td>Soup</td>
    <td>Chicken</td>
    <td>Leg</td>
    <td class="non-clicky">
        <p>Click</p>
    </td>
</tr>

What I need to do is get the value of the first td when I click on the class non-clicky. So I have the code:

alert($('.non-clicky:first').parent().children('td:first').val());

This code results in the value of "" -- empty string being returned and not the result 100101.

So, instead i tried the code:

alert($('.non-clicky:first').siblings(':first').val());

Again this resulted in the value being empty string, why is it .val() is returning an empty string instead of the correct result?

I tried the code below and this gives me the correct answer, but I am curious as to why val does not. What is the difference between val and text?

alert($('.non-clicky:first').siblings(':first').text());
// and 
alert($('.non-clicky:first').parent().children('td:first').text());

Note:

The code above makes use of $('.non-clicky:first') this was only for my testing purposes in the code it will be within a jquery click event.

3
  • It seems you have not read the documentation. Commented Feb 14, 2012 at 17:08
  • ""The .val() method is primarily used to get the values of form elements such as input"" is primarily used which implies it can be used for other things also. Commented Feb 14, 2012 at 17:10
  • And what makes you think that "the other" use is getting the text content of elements? But I see your point. Commented Feb 14, 2012 at 17:11

2 Answers 2

4

Use .text(), .val() is for getting the value of an input element.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @kevin-b, edited your answer a little but it hit the mark.
@aspect I've always wondered if there was possibly a better way to handle .val() vs .text(), but they've both been around for so long that changing either of them would cause major backwards compatibility issues and making .val() mimic .text() on non-inputs would just bloat the code.
0

Use text():

$('.non-clicky').click(function(){ alert($(this).siblings().first().text()); });

1 Comment

Was asking why i need to use text instead of val in the question. Not a solution to the problem.

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.