1

I am trying to put an array in a HTML table with javascript function but i dont khont how to insert this array? The idea is when i click on button Insert, it'll add one person's information into row. This's my table

   <script>
        //Array
        var a = [
            {name:"Micheal", age:20, hometown:"New York"},
            {name:"Santino", age:25, hometown:"Los Angeles"},
            {name:"Fredo",   age:29, hometown:"California"},
            {name:"Hagen",   age:28, hometown:"Long Beach"},
        ]

        //Insert data function
        function Insert_Data() {
          var table = document.getElementById("myTable");
          //Help......  
        }

    </script>
<!--Button Insert-->
    <input type="button" onclick="Insert_Data" value="Insert" /> 
    <!--Table-->
    <table id="myTable">
        <tr>
            <th>Full Name</th>
            <th>Age</th>
            <th>Country</th>
        </tr>

        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>

        <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>

5 Answers 5

5

You declare both thead and tbody and in function in loop fill the table

var a = [
    {name:"Micheal", age:20, hometown:"New York"},
    {name:"Santino", age:25, hometown:"Los Angeles"},
    {name:"Fredo",   age:29, hometown:"California"},
    {name:"Hagen",   age:28, hometown:"Long Beach"},
]

//Insert data function
function Insert_Data() {
  var table = document.getElementById("datas");
  table.innerHTML="";
  var tr="";
  a.forEach(x=>{
     tr+='<tr>';
     tr+='<td>'+x.name+'</td>'+'<td>'+x.age+'</td>'+'<td>'+x.hometown+'</td>'
     tr+='</tr>'

  })
  table.innerHTML+=tr;
  //Help......  
}
<input type="button" onclick="Insert_Data()" value="Insert" /> 
<!--Table-->
<table id="myTable">
    <thead>
       <tr>
        <th>Full Name</th>
        <th>Age</th>
        <th>Country</th>
    </tr>
    </thead>
   <tbody id="datas">

   </tbody>



</table>

Sign up to request clarification or add additional context in comments.

Comments

3

Demo proof: https://jsfiddle.net/psw41g6k/

function Insert_Data() {
         var table = document.getElementById("myTable");
         var rows = table.querySelectorAll('tr');
         console.log(rows)
         for (let i = 1; i < rows.length; i++) {
           rows[i].children[0].textContent = a[i-1].name
           rows[i].children[1].textContent = a[i-1].age
           rows[i].children[2].textContent = a[i-1].hometown
         }

       }

Comments

1

Create a dynamic element tr and td at the click of the button and append it to the table element in the document.

Use https://www.w3schools.com/jsref/met_node_appendchild.asp as a reference to understand how to create a dynamic element.

Comments

1

Here is a completely generic method, you can add a new key and it adds a new column to the data, no problem:

//Array
var myData = [
    {name:"Micheal", age:20, hometown:"New York", example: "extra"},
    {name:"Santino", age:25, hometown:"Los Angeles", example: "extra"},
    {name:"Fredo",   age:29, hometown:"California", example: "extra"},
    {name:"Hagen",   age:28, hometown:"Long Beach", example: "extra"},
]

//get references to the table and the head and body:
const myTable = document.getElementById('myTable');
const myTable_header = myTable.querySelector('thead')
const myTable_body = myTable.querySelector('tbody')

//Insert data function
function Insert_Data() {
  //Help...... :
  myTable_header.innerHTML = '';
  var tr = document.createElement('tr');
  const headers_data = Object.keys(myData[0]);
  headers_data.forEach((key) => {
    var th = document.createElement('th')
    th.innerHTML = key
    tr.appendChild(th);
  })
  myTable_header.appendChild(tr);
  myTable_body.innerHTML = '';
  for (let i = 0; i < myData.length; i++){
    var tr = document.createElement('tr');
    headers_data.forEach((key) => {
      var td = document.createElement('td');
      td.innerHTML = myData[i][key]
      tr.appendChild(td);
    });
    myTable_body.appendChild(tr);
  }
}
<!--Button Insert-->
<input type="button" onclick="Insert_Data()" value="Insert" /> 
<!--Table-->
<table id="myTable">
  <thead>
    <!-- Data is injected here -->
  </thead>
  <tbody>
    <!-- Data is injected here -->
  </tbody>
</table>

Comments

1

For dynamic tables if you gonna change your array frequently

let tableBody = a.reduce((rows, nextRow) =>{
                return rows += 
                    '<tr>' + 
                    Object.keys(nextRow).reduce((cols, nextCol) => { 
                        return cols += '<th>' + nextRow[nextCol] + '</th>'
                    }, '') + 
                    '</tr>'
            }, '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.