Generating Dynamic Table with Jquery

Asked

Viewed 134 times

0

I’m having the following problem, I’m doing a search engine ,to search for the client’s name ,so far so good ,I was able to bring the clients but they are in an array ,my problem is how do I divide each client into a separate line

I want it that way :

inserir a descrição da imagem aqui

But it’s coming like this :

inserir a descrição da imagem aqui

I have tried to use the chained $.each ,but it ends up duplicating the record ,if it is only caught one of the right record ,but the name has to be on the same line as your ID and AGE

success: function (data, status) {
                var valoresID;
                var arrID = [];
                var arrNome = [];
                var arrIdade = [];

                for (var i = 0; i < data.d.length; i++) {

                    var item = JSON.stringify(data.d[i]["ID"]);

                    arrID.push(data.d[i]["ID"]);
                    arrNome.push(data.d[i]["Nome"]);
                    arrIdade.push(data.d[i]["Idade"]);


                }
                $('.child').remove()
                $('.valorTr').after('<tr class="child"><td>'+JSON.stringify(arrID)+'</td><td>'+arrNome+'</td><td>'+arrIdade+'</td></tr>');

            }

1 answer

2


This happens because you are using the JSON.stringify that turns your array into a string.

To solve your problem you can do the following:

for (i =0; i < arrID.length; i++){
 $('.valorTr').after('<tr class="child"><td>'+arrID[i]+'</td><td>'+arrNome[i]+'</td><td>'+arrIdade[i]+'</td></tr>');
}

A better solution would be for you to only work with an array containing the object you recover:

dadosTabela = []

// código omitido (loop dos dados)
dadosTabela.push(dados = {
  "Id": 1,
  "Nome": "Laerte",
  "Idade": 23
})
dadosTabela.push(dados = {
  "Id": 2,
  "Nome": "João",
  "Idade": 18
})

dadosTabela.forEach(x => console.log(x['Id'] + '\t' + x['Nome'] + '\t' + x['Idade']))

  • It worked, thank you I’ll see your second form.

Browser other questions tagged

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