User987
User987

Reputation: 3825

Getting ID value of the clicked row in jQuery

I have a table td's set up like this:

@foreach (var item in ViewBag.WatchListCompetitor)
{
    <tr role="row" class="odd">
        <td class="" tabindex="0">@item.SentWord</td>
        <td class="sorting_1">@item.Comment</td>
        <td class="sorting_1">@item.Rating</td>
        <td class="sorting_1">@item.SellerFeedback</td>
        <td class="sorting_1 deleteAction"><i class="fa fa-close"></i></td>
        <td class="idRow" style="display:none;" id="@item.WatchListID">@item.WatchListID</td>
    </tr>
}

And I've defined an onclick event like this to try to get the idRow value when the "delete action" is triggered...

$(document).ready(function () {
    $('.deleteAction').click(function () {

        console.log($(this).closest("td"));
    });
});

The result that I get is:

Object { length: 1, prevObject: Object, context: <td.sorting_1.deleteAction>, 1 more… }

How can I fetch the td idRow value when event is triggered?

Upvotes: 0

Views: 192

Answers (4)

Akshay Tilekar
Akshay Tilekar

Reputation: 2020

you can use .prop() or .attr() of JQuery to get desired paramas.The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

$('.deleteAction').click(function () {
    var $idRowTd = $(this).closest(".odd").find(".idRow").attr("id"); //Before/upto jQuery 1.6;
var $idRowTd = $(this).closest(".odd").find(".idRow").prop("id");//for jQuery 1.6 and above
});

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382514

You can use closest to get to the row, then find to get to the idRow td:

$('.deleteAction').click(function () {
    var $idRowTd = $(this).closest(".odd").find(".idRow");
    var id = $idRowTd.prop("id");
    // use the element and id here
});

Always prefer to use closest and find rather than looking for the siblings: when you change the HTML (for example you wrap an element), the code stays valid. For the same reason it's better to look for a class (for example ".odd") than to look for a tag (for example "tr").

Upvotes: 4

Danny Drinkwater
Danny Drinkwater

Reputation: 41

Try:

$(document).ready(function () {
    $('.deleteAction').click(function () {
        console.log($(this).closest('tr').find('.idRow').attr('id'));
    });
});

Upvotes: 1

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

Find the sibling() with the class idRow and retrieve its id

$('.deleteAction').click(function () {

    console.log($(this).siblings("td.idRow").attr('id'));
});

Upvotes: 1

Related Questions