views:

141

answers:

4

I have the following HTML in a JSP file:

<div class="custList">
   <table class="dataGrid">
      <c:forEach var="cust" items="${custList}">
         <tr>
            <td>${cust.number}</td>
            <td>${cust.description}</td>
            <td>${cust.type}</td>
            <td>${cust.status}</td>
        </tr>
     </c:forEach>
  </table>
</div>

I need to be able to trigger a 'click' event on each of the dynamically created <tr> tags and also be able to access the values of the <td> tags (of the clicked <tr>) from within the javascript function. I have this function already but sadly it doesn't seem to be working.

$(document).ready(function() {
    $("div.custList > table > tr").live('click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

Thanks for your help, Randall

+1  A: 

$(this).find('td') will give you an array of td's in the tr.

VeeWee
Note that this will also return all `<td>` of any **nested** tables. The `children()` returns the *immediate* children, like as `$(this).find('> td')` would do.
BalusC
+3  A: 

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

BalusC
+1 Just discovered this the other day.
sje397
didn't know about the insertion of the <tbody> tag. Thanks for the help works great. :)
Randall Kwiatkowski
You're welcome.
BalusC
A: 

You could maybe try jQuerys delegate() function, like so:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

Delegate works in the same way as live() except live()cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.

webfac
A: 

Since TR elements wrap the TD elements, what you're actually clicking is the TD (it then bubbles up to the TR) so you can simplify your selector. Getting the values is easier this way too, the clicked TD is this, the TR that wraps it is this.parent

Change your javascript code to the following:

$(document).ready(function() {
    $(".dataGrid td").click(function() {
        alert("You clicked my <td>!" + $(this).html() + 
              "My TR is:" + $(this).parent("tr").html());
        //get <td> element values here!!??
    });
});​
JKirchartz