Home > Enterprise >  Create table with given data in HTML
Create table with given data in HTML

Time:05-14

everyone! I am quite new to coding and I would like some help. Unfortunately, I don't have any code. Here's what I have to do.

I am given a variable data (similar to a dict in Python) and I have to create a table based on that data. I will leave an example below.

If you need any more info, I will provide.

Thanks!

users = 
[
    { 
      "name" : "N0",
      "dateOfBirth" : "D0",
      "car" : "C0"
    },
    { 
      "name" : "N1",
      "dateOfBirth" : "D1",
      "car" : "C1"
    },
    { 
      "name" : "N2",
      "dateOfBirth" : "D2",
      "car" : "C2"
    },
    { 
      "name" : "N3",
      "dateOfBirth" : "D3",
      "car" : "C3"
    }
]

CodePudding user response:

You can use jquery to add the data to the table dynamically. You can change the users value with same format the table will get created automatically.

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>

<table id="myTable">
  <tr>
    <th>Name</th>
    <th>Date</th>
    <th>Car</th>
  </tr>
</table>

<script>
const users = 
[
    { 
      "name" : "N0",
      "dateOfBirth" : "D0",
      "car" : "C0"
    },
    { 
      "name" : "N1",
      "dateOfBirth" : "D1",
      "car" : "C1"
    },
    { 
      "name" : "N2",
      "dateOfBirth" : "D2",
      "car" : "C2"
    },
    { 
      "name" : "N3",
      "dateOfBirth" : "D3",
      "car" : "C3"
    }
]

users.forEach((element)=>{

$("#myTable").append(`
<tr>
<td>${element.name}</td>
    <td>${element.dateOfBirth}</td>
    <td>${element.car}</td>
 </tr>
`)

})


</script>

CodePudding user response:

Since you are new to coding rather than finding answers here and there I will suggest you to start learning how to code, Links to "TABLE" lecture is already in your comments please follow that, also for the answer to your question going to write the code below:

HTML:

<table>
  <tr>
    <th>Name</th>
    <th>DateOfBirth</th>
    <th>Car</th>
  </tr>
  <tr>
    <td>N0</td>
    <td>D0</td>
    <td>C0</td>
  </tr>
  <tr>
    <td>N1</td>
    <td>D1</td>
    <td>C1</td>
  </tr>
  <tr>
    <td>N2</td>
    <td>D2</td>
    <td>C2</td>
  </tr>
  <tr>
    <td>N3</td>
    <td>D3</td>
    <td>C3</td>
  </tr>
</table>

CSS :

td, th {
  border: 1px solid #000;
  text-align: center;
  padding: 5px;
}
  •  Tags:  
  • html
  • Related