Complete table with loop using jquery

Asked

Viewed 65 times

-1

In this table:

<table>
    <thead>
        <tr>
            <th>marca</th>
            <th>ano</th>
            <th>cor</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

How to loop in jquery to insert this into tbody?

        <tr>
            <td>fiat</td>
            <td>2001</td>
            <td>verde</td>
        </tr>
        <tr>
            <td>ford</td>
            <td>2002</td>
            <td>azul</td>
        </tr>
        <tr>
            <td>VW</td>
            <td>2003</td>
            <td>preto</td>
        </tr>

Data is inside an object. Ex:

0: {marca: "fiat", ano: "2001", cor:"verde"}
1: {marca: "ford", ano: "2002", cor:"azul"}
2: {marca: "VW", ano: "2003", cor:"preto"}

1 answer

1


Use the method append or appendTo. Since jQuery already parses your strings into HTML, you just need to write the string in the proper format, and then attach it to an element you search for with jQuery.

var carros = [
  { marca: "fiat", ano: "2001", cor:"verde" }, 
  { marca: "ford", ano: "2002", cor:"azul" }, 
  { marca: "VW", ano: "2003", cor:"preto" }
]

var htmlCarros = carros.map(carro => 
  `<tr>
    <td>${carro.marca}</td>
    <td>${carro.ano}</td>
    <td>${carro.cor}</td>
  </tr>`
)

$('#minha_tabela').append(htmlCarros)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>marca</th>
      <th>ano</th>
      <th>cor</th>
    </tr>
  </thead>
  <tbody id="minha_tabela">

  </tbody>
</table>

  • 1

    It was perfect. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.