Skip to content
Advertisement

Alpine JS Table Data Binding

I’m a newbie in Alpine JS. I want to design my table with detailed rows like this:

enter image description here

I wrote a simple HTML table like this:

       
<table>
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Username</th>
  </tr>
  
  <tr>
    <td>1</td>
    <td>Leanne Graham</td>
    <td>Bret</td>
  </tr>
    
  <tr>
    <td colspan="3">User Email : Sincere@april.biz</td>    
  </tr>
</table>

I tried to bind my JSON to this table. At that point, it did not work as expected. Here is what I tried:

<table>
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Username</th>
  </tr>
  
   <template x-for="u in users" :key="u.id">
    
    <tr>    
      <td x-text="u.id"></td>   
      <td x-text="u.name"></td>
      <td x-text="u.username"></td>    
    </tr>
    <tr>
       <td x-text="u.email" colspan="3"></td>    
    </tr>
        
   </template>
  
</table>

With this code, the output will look like this:

enter image description here

User detail fields are building after the total of the list. And there is no data like user email in there. What am I missing? How can I fix this code?

You can access the Codepen project from here.

Any help would be appreciated!

Advertisement

Answer

I’ve been tried to change a few about HTML TABLES, Finally, I reached your the expected result. Here’s the codepen link: codepen

  
<table>
      <thead>
         <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Username</th>
         </tr>
      </thead>
      <template x-for="(user, index) in users" :key="index">
         <tbody>
            <tr>
               <td x-text="user.id"></td>
               <td x-text="user.name"></td>
               <td x-text="user.username"></td>
            </tr>
            <td x-text="user.email" colspan="3"></td>
         </tbody>
      </template>
   </table>

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement