Search code examples
jquerydisplaytag

How to select a cell content in a table when there is no id or class using jquery


I have a table generated by displaytags and it looks like below.

<tbody>
  <tr class="coldata">
    <td>02063873320</td>
    <td>ORD81268679</td>
    <td>80%</td>
    <td>6</td>
    <td>84070063962913</td>
    <td><img src="xyz"/></td>
  </tr>
  <tr>
    .
    .
    .
  </tr>

Each row has an image in the last cell and when i click on the cell i want to call a Jquery function which will send the 5th cell's value in that row to an action class.

i want to know how to select the 5th cell and function to an action class. Can anyone suggest the selector and function to call action class


Solution

  • If the rows all have that coldata class, you can get the fifth cells (index 4) using :eq like this:

    var fifthCells = $("tr.coldata td:eq(4)");
    

    ...and then hook their click event, and navigate from there:

    fifthCells.click(function() {
        var $td = $(this); // The specific `td` that was clicked
        // ...do something with that specific `td`
    });
    

    If it's not always the fifth cell but always the one before the last, you can use last-of-type:

    var lastCells = $("tr.coldata td:last-of-type").prev('td');
    

    Or if they're the only ones prior to ones with img elements in them:

    var cellsWithImages = $("tr.coldata td img").closest("td").prev('td');
    

    ...and so on.


    Side note: If the contents of the table are dynamic (or arguably even if they aren't), it may be useful to use a delegated handler. Here's the delegated click handler for the fifth td in each row:

    // fifthCells
    $("table.some-class").on("click", "tr.coldata td:eq(4)" function() {
        // `this` is the DOM element for the td that was clicked
    });