Vincent Bowman
Vincent Bowman

Reputation: 49

$(this) reference

$('td').click(function(){    
    $('input:radio').click(function(){    
    })
})

If I use $(this) after second line it will refer to the radio button. How to refer to the td element from that line? I am trying to add an id to td element but it adds this to the radio button.

Upvotes: 0

Views: 83

Answers (3)

John S
John S

Reputation: 21482

There are two ways to do it:

As others have shown, you can use a closure:

$('td').click(function() {
    var td = this; // Creates a closure
    $('input:radio').click(function(event) {
        // this and event.target refer to the radio button
        // td refers to the <td> element
    });
});

Or you can use $.prox():

$('td').click(function() {
    $('input:radio').click($.proxy(function(event) {
        // this refers to the td
        // event.target refers to the radio button
    }, this));
});

Upvotes: 1

mattgmg1990
mattgmg1990

Reputation: 5876

$('td').click(function(){    
    var tdElement = $(this);
    $('input:radio').click(function(){    
        // Do whatever you like with tdElement here
    })
})

Upvotes: 0

kinakuta
kinakuta

Reputation: 9037

Save a reference to this before the radio button handler:

$('td').click(function () {
    var self = this;
    $('input:radio').click(function () {
        // self refers to 'this' from the td selection here
    });
});

I'm not sure this is what you really want to do, however, as what you're doing is assigning a click handler for a click on a radio button on a click on the td. Is that what you had in mind?

Upvotes: 4

Related Questions