thebdawk05
thebdawk05

Reputation: 135

How do I get jQuery to return a table row element when using "this?"

I'm using an asp.net list view control and within it I'm building a table element.

<asp:ListView ID="ListView1" runat="server">
    <LayoutTemplate>
        <table>
            <tr class="header">
                <td></td>
            </tr>
            <tr id="itemPlaceHolder runat="server">
        </table>
    </LayoutTemplate>
    <ItemTemplate>
        <tr onclick="RowClick();">
    </ItemTemplate>
</asp:ListView>

I'm calling a javascript function behind the row click.

function RowClick() {
    var tds = $(this).children('td');
}

My problem is that $(this) within my RowClick() function doesn't return a tr element, it's returning the entire window instead. How can I achieve this? Am I approaching the situation wrong? Is this not possible and I'm chasing ghosts? Thanks! Forgive my markup, still haven't quite gotten the hang of it yet.

Upvotes: 2

Views: 1404

Answers (4)

MonkeyZeus
MonkeyZeus

Reputation: 20737

I would strongly advise against mucking up your HTML with JS calls and jQuery handles this beautifully:

$(document).ready(function(){

    // create the function
    function RowClick(target){
        var tds = target.children('td');

        // another option :)
        var tds = target.find('td');
    }

    // listen for a <tr> to get clicked within the <table> -> <ItemTemplate> combo and pass the <tr> target to the function
    $('table ItemTemplate').on('click', 'tr', function(){
        RowClick($(this));
    });

});

Upvotes: 0

streetlogics
streetlogics

Reputation: 4730

This isn't very "jQuery'esque" in terms of handling the code. A more "proper" way would be to do something like this:

<tr class="row-click">

and in your javascript:

$(function(){
    $(".row-click").each(function(){
        $(this).on("click",function(){
            var tds = $(this).children('td');
            //Code goes here...
        });
    });
});

alternatively, if you want to keep the "RowClick" function, you could do:

$(function(){
    $(".row-click").each(function(){
        $(this).on("click",function(){
            RowClick($(this));
        });
    }
});
function RowClick(element){
    var tds = $(element).children('td');
    //Code goes here...
}

Upvotes: 0

Grim
Grim

Reputation: 1986

Using jQuery? hm, let me see.

jQuery("tr").click(RowClick);

Regards.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

you need to pass a custom execution context for the handler invokation, you use Function.call() to do this

<tr onclick="RowClick.call(this);">

Upvotes: 6

Related Questions