Unknown User
Unknown User

Reputation: 3658

jquery - get the value of <tr> in a html table

I have a AJAX created table.

And I need to call a ajax request on the those table which was created through ajax.

Through this I figured out to call the click function on dynamically created HTML element.

Table looks similar like this.

<table>
    <thead>
        <th>Sr. No</th>
        <th>Label</th>
    </thead>
    <tbody>
        <tr value="1">
            <td>1.</td>
            <td>One</td>
        </tr>
        <tr value="2">
            <td>2.</td>
            <td>Two</td>
        </tr>
    </tbody>
</table>

I've assigned value to the tr and now I want to create another ajax request on click of the tr. And based on the value I'm running a query to get the data.

Challenge I'm facing is that I'm not able to get the value of the tr.

Here's the code I tried with.

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).val())
    })
})

Here's the fiddle.

Even in the fiddle I'm unable to get the value of a tr.

Please help me to find where I'm going wrong.

Thanks in advance.

Upvotes: 0

Views: 1371

Answers (4)

Sridhar R
Sridhar R

Reputation: 20408

Try this use.attr()

alert($(this).attr("value"));

Upvotes: 0

Kaushal Khamar
Kaushal Khamar

Reputation: 2125

Use text() property of tr instated of val() property.

see this Fiddle

see this code

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
       alert($(this).text())
    })
})

Upvotes: 0

WIRN
WIRN

Reputation: 947

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).attr("value"));
    })
})

see http://jsfiddle.net/tqQm5/4/

Upvotes: 0

Felix
Felix

Reputation: 38102

You can use .attr() instead:

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).attr('value'))
    })
})

Updated Fiddle

but actually you should use data-* HTML5 attribute:

<tr data-value="1">

then retrieve it using .data():

$(document).ready(function() {
    $('.table').on('click', 'table tbody tr', function() {
        alert($(this).data('value'))
    })
})  

Updated Fiddle

Upvotes: 4

Related Questions