Raj
Raj

Reputation: 837

How to get row data of a html table in javascript

I have a table like this

<tr class="odd">
    <td class="  sorting_1">opps</td>
    <td class="center "> <a href="#" onclick="tst(this)" class="btn btn-warning">
    <i class="icon-edit icon-white">      
    </i> Edit</a>

    </td>
</tr>

On click of that hyperlink i need the td values of the row.

This javascript i tried

 $(document).ready(function () {
     $("#tblTest td:nth-child(2)").click(function (event) {
         //Prevent the hyperlink to perform default behavior
         event.preventDefault();
         var $td = $(this).closest('tr').children('td');
         var sr = $td.eq(0).text();
         alert(sr);
     });
 });

This one works if i put in Table click event. I need on click of that hyperlink it should happen. How to achieve this ? Thanks in Advance.

without iterating row by row if any method is there to get it ?

Upvotes: 0

Views: 2858

Answers (2)

palaѕн
palaѕн

Reputation: 73966

Try this:

$("a.btn").click(function (event) {
    //Prevent the hyperlink to perform default behavior
    event.preventDefault();
    var $td = $(this).parent().closest('tr').children('td');
    var sr = $td.eq(0).text();
    alert(sr);
});

DEMO HERE

Upvotes: 1

Adil
Adil

Reputation: 148180

You are binding click event to td bind it to a

Change

$("#tblTest td:nth-child(2)").click(function (event) {

To

$("#tblTest td:nth-child(2) a").click(function (event) {

Upvotes: 1

Related Questions