Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Click event on <tr> elements with in a table and getting <td> element values

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!!??     }); }); 

Update (Jan 2016): jQuery.live is deprecated (as noted here:http://api.jquery.com/live/)

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

like image 776
Randall Kwiatkowski Avatar asked Aug 11 '10 13:08

Randall Kwiatkowski


People also ask

How can get TD value from TR in jQuery?

var Something = $(this). closest('tr'). find('td:eq(1)'). text();

How to get particular td value in JavaScript?

var t = document. getElementById("table"), d = t. getElementsByTagName("tr"), r = d. getElementsByTagName("td");

How to get table row td value in JavaScript?

each(function() { valuesByRowID[this.id] = $(this). find("> td"). map(function() { // Option 1: Getting the value of the `value` attribute: return this. getAttribute("value"); // or return $(this).


1 Answers

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').

like image 198
BalusC Avatar answered Oct 06 '22 00:10

BalusC