Tuesday, August 2, 2022

[FIXED] How to replace <td> values in a table with jQuery (in every Rows)?

Issue

I have a table with multiple columns, one column named: ‘Type’. The values in Type column could be: 1 or 2. I want to replace the value “1” to “Information” and the value “2” to “Problem” in every row with jQuery, how can I do that?


Solution

There are many ways to achieve something like this. Here is one example. It first looks for the index by comparing the text of each cell in the table header. then it gets all cells in the table body with the index in each table row and replaces the content if it is "1" or "2". There are for sure even shorter or faster methods.

// Find index of column with "Type"
let index = -1;
let th = $('#myTable thead tr th');
for (let i=0; i<th.length; i++) {
    if ($(th[i]).text() == 'Type') {
    index = i;
    break;
  }
}

// If index is greater then -1 we found the column
if (index > -1) {
  // Get all the table cells in each row at the specific index (need to add +1 to the index)
  let td = $('#myTable tbody tr td:nth-child(' + (index+1) + ')');
    for (let i=0; i<td.length; i++) {
      // Compare content and replace it
      if ($(td[i]).text() == '1') {
        $(td[i]).text('Information');
      }
      else if ($(td[i]).text() == '2') {
        $(td[i]).text('Problem');
      }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>ID</th>
      <th>Type</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>John</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>Maria</td>
    </tr>
    <tr>
      <td>2</td>
      <td>2</td>
      <td>Walter</td>
    </tr>
    <tr>
      <td>3</td>
      <td>1</td>
      <td>Julia</td>
    </tr>
  </tbody>
</table>



Answered By - Jan
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.