Home > Enterprise >  Add Items from Array to HTML table
Add Items from Array to HTML table

Time:09-25

How I can iterate through an array in JavaScript while adding each element to an HTML table with a button? (i.e. click a button and "Rigatoni" gets added to a table.)

function New_Item() {

  const Ingredients = ["Rigatoni", "Pesto", "Crushed Tomatoes", "Pasta Water", "Mozzarella Cheese", "Fresh Chopped Basil"]
  for (var x = 0; x < Ingredients.length; x  )
    var table = document.getElementById("myTable");
  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  cell1.innerHTML = Ingredients;
}
<table id="myTable">
  <header>
    <tr>
      <td>Ingredient</td>
    </tr>
  </header>
  <footer>
  </footer>
</table>
<button type="button" onclick="New_Item()">Add Ingredient</button>

CodePudding user response:

If I understand what you asked, this is my solution.

<script>
var current=0;
const Ingredients = ["Rigatoni", "Pesto", "Crushed Tomatoes", "Pasta Water", "Mozzarella Cheese", "Fresh Chopped Basil"];
function New_Item() {
  if (current < Ingredients.length) {
  var table = document.getElementById("myTable");
  var row = table.insertRow(current 1);
  var cell1 = row.insertCell(0);
  cell1.innerHTML = Ingredients[current];
    current  ;
  }
}
</script>
<table id="myTable">
  <header>
    <tr>
      <td>Ingredient</td>
    </tr>
  </header>
  <footer>
  </footer>
</table>
<button type="button" onclick="New_Item()">Add Ingredient</button>

CodePudding user response:

You can use the code below.

<table id="myTable">
<header>
    <tr>
    <td>Ingredient</td>
    </tr>
</header>
<tbody>
    
</tbody>
</table>
<button type="button" onclick="New_Item()">Add Ingredient</button>

<script>
const Ingredients = ["Rigatoni", "Pesto", "Crushed Tomatoes", "Pasta Water", "Mozzarella Cheese", "Fresh Chopped Basil"];

function New_Item() {
  var tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];

  Ingredients.forEach(function(cellData) {
    var row = document.createElement('tr');

    var cell = document.createElement('td');
    cell.appendChild(document.createTextNode(cellData));
    row.appendChild(cell);

    tableBody.appendChild(row);
  });
}
</script>
  • Related