Skip to content
Advertisement

Edit a table with Jquery find() then add cell with data from an array with before()

I am trying to insert a column of cells with data from an array. I have tried using a for loop, but that just put all the data of the array in each new cell. My goal is to have the new cells display row_header1, row_header2, or row_header3 respectively.
Can anyone help me with this issue? Thank you.

-for loop I’vs tried.

for (var i = 0, len = arr1.length; i < len; i++) {
      $("tr").find("td:first").before('<td>' + arr1[i] + '</td>')

var arr1 = ["row_header1", "row_header2", "row_header3"];

$(document).ready(function() {
  $("#btn").click(function() {
    var i = 0,
      len = arr1.length;
    i < len;
    i++;

    $("tr").find("td:first").before('<td>' + arr1[i] + '</td>')
  });
});
td,
th {
  padding: 4px;
  border: solid;
  width: 50px;
  height: 50px;
}

table {
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">+</button>
<table id='table'>
  <tr>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
  <tr>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
  <tr>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
</table>

Advertisement

Answer

I think you need to select the right tr each time when you want to assign value

var arr1 = ["row_header1", "row_header2", "row_header3"];

$(document).ready(function() {
  $("#btn").click(function() {
    var i = 0,
      len = arr1.length;
      while(i< len){
        $("tr:eq("+i+")").find("td:first").before('<td>' + arr1[i] + '</td>');
        i++;
     }
  });
});
td,
th {
  padding: 4px;
  border: solid;
  width: 50px;
  height: 50px;
}

table {
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">+</button>
<table id='table'>
  <tr>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
  <tr>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
  <tr>
    <td>
    </td>
    <td>
    </td>
    <td>
    </td>
  </tr>
</table>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement