Matt Seymour
Matt Seymour

Reputation: 9395

jQuery val returns empty string

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.

Upvotes: 1

Views: 2397

Answers (2)

Kevin B
Kevin B

Reputation: 95031

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

Upvotes: 4

elclanrs
elclanrs

Reputation: 94101

Use text():

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

Upvotes: 0

Related Questions