Flibbertigibbet
Flibbertigibbet

Reputation: 35

Get the value of table cell in a row (JS or jQuery)

I have a table that incorporates 50 identical

<tr>
    <td>#</td>
    <td>#</td>
    <td>123123</td>
</tr>
...

and now I am able to get the value of a specific row like this

$("#tableId tbody tr").each(function(){
    var a = $(this).children();
    var arr =a[2].innerText; //get each row
    a[2].innerText = statename // get the third cell in each row
});

In this case, statename is an object with 50 states names. All I want to do now is to substitute that 123123 to each state name inside the object. So that it looks like this:

<tr>
    <td>#</td>
    <td>#</td>
    <td>Alabama</td>
</tr>
<tr>
    <td>#</td>
    <td>#</td>
    <td>Alaska</td>
</tr>
<tr>
    <td>#</td>
    <td>#</td>
    <td>Arizona</td>
</tr>
...

I tried to loop within the jQuery but it did not work. Please help, thank you very much.

Upvotes: 2

Views: 1539

Answers (3)

nabais
nabais

Reputation: 2037

Make sure your variable statename is an array, and don't forget the index of the state

// find elements
statename = ["Alabama", "Alaska", "Arizona"]
$("#tableId tbody tr").each(function(index){
    var a = $(this).children();
    var arr =a[2].innerText; //get each row
    a[2].innerText = statename[index] // get the third cell in each row
});

Upvotes: 0

EugenSunic
EugenSunic

Reputation: 13693

By using vanilla js, you can easily get the last td elements in tr, loop through them and assign new values to the nodes

const stateNames = ['Alabama', 'Alaska', 'Arizona'];
document.querySelectorAll('tr td:last-child')
  .forEach((x, i) => x.textContent = stateNames[i])
<table>
  <tr>
    <td>#</td>
    <td>#</td>
    <td>123123</td>
  </tr>

  <tr>
    <td>#</td>
    <td>#</td>
    <td>123123</td>
  </tr>
  <tr>
    <td>#</td>
    <td>#</td>
    <td>123123</td>
  </tr>
</table>

Upvotes: 1

T&#226;n
T&#226;n

Reputation: 1

You can try to use each method with find method, in the selector name, you can search the last <td> element by td:last. Like this:

var statenames = ['Alabama', 'Alaska', 'Arizona'];

$("#tableId tbody tr").each(function(index){
    $(this).find('td:last').text(statenames[index]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="tableId">
  <tbody>
    <tr>
      <td>#</td>
      <td>#</td>
      <td>123123</td>
    </tr>
    <tr>
      <td>#</td>
      <td>#</td>
      <td>123123</td>
    </tr>
    <tr>
      <td>#</td>
      <td>#</td>
      <td>123123</td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions