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

Time:09-19

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>

CodePudding user response:

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>

  • Related