views:

2568

answers:

3

Hi,

Is it possible to add a jQuery function so that a click in a table cell will invoke a hidden <a href="javascript: ..." /> element (that is a descendant of the TD) ?

I've tried with

$('#table td').click(function() { $(this).find('a').click(); });

An other variants, but to no luck.

--larsw

+5  A: 

Why don't you move your JavaScript code out of the href attribute and into your click event? jQuery was made to write unobtrusive JavaScript.

Edit:

No, but really, consider removing those hidden links in favor of unobtrusive JavaScript. Here are the relevant parts of Corey's example rewritten:

JS:

  $(document).ready(function() {
    $('table td').click(function(event) {
      alert($(this).html())
    })
  })

HTML:

<table border="1">
  <tr>
    <td>a1</td>
    <td>a2</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
  </tr>
</table>
Zach Langley
+2  A: 
<html>
<head></head>
<body>
<table border=1>
    <tr>
        <td>a1<a href=# onclick='alert("a1")' /></td>
        <td>a2<a href=# onclick='alert("a2")' /></td>
    </tr>
    <tr>
        <td>b1<a href=# onclick='alert("b1")' /></td>
        <td>b2<a href=# onclick='alert("b2")' /></td>
    </tr>
</table>
<script src="scripts/jquery-1.2.6.min.js" ></script>
<script>
    $(function(){
        $('table td').click(function(){ $(this).find('a').click()});
    })
</script>
</body>
</html>

I have it working fine with that clip above. However see your jQuery selector has a # in front of it , which would be failing unless your table has an id of 'table'.

Having said that, there is probably a better way to do what your after than hidden a tags with javascript embedded in them.

Corey Downie
Good observation Corey. I agree it seems that the # is causing the problem. It should be $('table td).
Cyril Gupta
+1  A: 

This would be a workaround if you want to avoid adding an onclick:

$('#table td').click(function() { 
    $(this).find('a').each(function(){ window.location = this.href; });
});
Cristian Libardo
This did the trick for me. I like to avoid the onclick event on every <a> element and I needed it for <a href="mailto:[email protected]"><a> like these. It just worked. Thanks
Bas Jansen