Leonardo Santos Leonardo Santos - 1 year ago 115
Ajax Question

innerHTML doesn't generate <tr> and <td> properly

I need to generate a table whose tbody's rows are generate through a for(). Because in this rows will be data coming from an array.

This is my code:

JS:

alunos = JSON.parse(req.responseText);
document.getElementById("tableModal").innerHTML =
"<div class='table-responsive'>"+
"<table class='table table-striped table-hover table-condensed table-order'>"+
"<thead>"+
"<tr>"+
"<th>Aluno</th>"+
"<th>Celular</th>"+
"<th>Turma</th>"+
"<th>Status</th>"+
"</tr>"+
"</thead>"
"<tbody>";
for(i = 0; i<alunos.length;i++) {
document.getElementById("tableModal").innerHTML +=
"<tr>" +
"<td>" + alunos[i].nome + "</td>" +
"<td>" + alunos[i].celular + "</td>" +
"<td>" + turma + "</td>" +
"<td>Status</td>" +
"</tr>";

}
document.getElementById("tableModal").innerHTML += "</tbody></table></div>";


HTML:

<div class="modal fade" id="modalMsg" role="dialog">
<div class="modal-dialog modal-lg">

<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title" id="tituloModal"></h4>
</div>
<div class="modal-body">
<div id="tableModal"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
</div>
</div>

</div>
</div>


Until the for statement, everything works as I want. But the tr and the td are not generated.

Answer Source

You have to do it in one go:

var req = {
  responseText : '[{"nome":"name","celular":"1233456"},{"nome":"name","celular":"1233456"}]'
}
var turma = "x";
alunos = JSON.parse(req.responseText);
var html= "<div class='table-responsive'>" +
  "<table class='table table-striped table-hover table-condensed table-order'>" +
  "<thead>" +
  "<tr>" +
  "<th>Aluno</th>" +
  "<th>Celular</th>" +
  "<th>Turma</th>" +
  "<th>Status</th>" +
  "</tr>" +
  "</thead>"
"<tbody>";
for (i = 0; i < alunos.length; i++) {
  html +=
    "<tr>" +
    "<td>" + alunos[i].nome + "</td>" +
    "<td>" + alunos[i].celular + "</td>" +
    "<td>" + turma + "</td>" +
    "<td>Status</td>" +
    "</tr>";

}
document.getElementById("tableModal").innerHTML += html+"</tbody></table></div>";
<div class="modal fade" id="modalMsg" role="dialog">
  <div class="modal-dialog modal-lg">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title" id="tituloModal"></h4>
      </div>
      <div class="modal-body">
        <div id="tableModal"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
      </div>
    </div>

  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download