Search code examples
jqueryjqgrid

Fetching value from particular cell using jquery


note : firstly i select the row and below code will be used to fetch id

var allocationid = $(this).parents("tr").children("td").eq(0).text();

my jquery code .. using eq .

but i dont want to use eq . i want in dynamic way. fetch with the help of column name

//table format table has thead and tbody tag

<table>
<thead>
      <tr>
          <th>ID</th>
          <th>name</th>
      </tr><br>
<thead>
<tbody>
     <tr>
     <td>01</td>
     <td>joe</td>
     </tr>
</tbody>
</table>
let colName_NPDId = 'NPDId';
    let index1 = $(this).closest("table").find(`thead tr th:contains(${colName_NPDId})`).index();
    let npdid = $(this).closest("tr").children("td").eq(index1).text();

this code I Used (reference of this comment) but this code fetch value of hidden column only(jqgrid). please help me out


Solution

  • Get the index of the column name from the header, then use that in .eq().

    let colName = 'ID';
    let index = $(this).closest("table").find(`thead tr th:contains(${colName})`).index();
    let allocationId = $(this).closest("tr").children("td").eq(index).text();
    

    Explanation:

    • $(this).closest("table") gets the enclosing table.
    • .find(thead tr th:contains(${colName})) finds the heading cell containing the column name we care about.
    • .index() returns its position in the row.
    • $(this).closest("tr") gets the current row.
    • .children("td") returns all the <td> elements in the current row
    • .eq(index) returns the element with the same index we determined above
    • .text() returns its text content.