2

I have a table row that has background color on hover. When user clicks within the background color area, it should grab the link of the anchor tag inside the row and take the user there.. How do I do this?

<tr id="ClickableRow">
    <td>
<a href="http://somesite.com">Go Here</a>
<p> To find about all the interestng animals found in this tourist attractions including 
zebra, giraffe.....
....
</p>
    </td>
</tr>

How do I grab the anchor tab href value ?

 $('tr #ClickableRow').click(function () {
         window.location.href=Anchor tag's href value

        });
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anju Thapa
  • 257
  • 6
  • 17
  • 32

4 Answers4

9

Ok first of all there's no need to specify a tr in the selector if you use an id anyway. And if you want to you should write that together without whitespace as the tr got that id.

Second, you need to use this and find() to select the first link inside the clicked table-row and get it's href attribute:

$('tr#ClickableRow').click(function () {
  var url = $(this).find('a:first').attr('href');
  window.location.href = url;
});

The following also works:

location = $(this).find('a:first').attr( 'href' );

See: Javascript: Setting location.href versus location

Community
  • 1
  • 1
bardiir
  • 14,556
  • 9
  • 41
  • 66
2

In your case

$('#ClickableRow').click(function () {
   window.location = $("#ClickableRow a:first").attr('href');
});

You can test on http://jsfiddle.net/.

To make it look like clickable you can add this

JavaScript:

$('#ClickableRow').hover(
    function () {
        if ($(this).find("th").length > 0) return;
        $(this).addClass("gridRowHover");
    },
    function () { $(this).removeClass("gridRowHover"); }
);

CSS

.gridRowHover{
    cursor: pointer;
 }

Generic function, to make any row of table clickable

function bindRowClick(itemId, eventHandler) {  
    var binder = "tr"; 
    $("#" + itemId).find(binder).click(eventHandler); 
}

ItemId will be your table id and eventHandler is the function to be executed.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
1

how about:

$('#ClickableRow').click(function () {
     window.location = $('a:first', this).attr('href');
});
John Boker
  • 82,559
  • 17
  • 97
  • 130
0

you need to also remove space between tr and #ClickableRow other wise it will take as children element.

$('tr#ClickableRow').click(function () {
    window.location = $(this).find('a').attr("href");
});
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58