Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script misaligns table

I have basic table

html

<table id="damageList">
  <tr>
   <td>#</td>
   <td>Type</td>
   <td>Delete</td>
  </tr>
</table>

which I'm trying to fill by data dynamically with

js

function addDamage(){
  var trA= "<tr>";
  var trB= "</tr>";
  var td1= "<td>"+nmbr+"</td>";
  var td2= "<td>"+type+"</td>";
  var td3= "<td><a href='#confirmDialog'>X</a></td>";

  $("#damageList").append(trA, td1, td2, td3, trB);

  nmbr++;
}

(the variable nmbr is numbering of lines and goes from 1, type is solved dynamicaly elsewhere)

The problem is, I'm not getting proper table.

What I get is this:

<table id="damageList">
  <tr>
   <td>#</td>
   <td>Type</td>
   <td>Delete</td>
  </tr>
  <tr></tr>
  <td>1</td>
  <td>K</td>
  <td>
   <a href="#confirmDialog">X</a>
  </td>
</table>

Could somebody please tell me, where did I make a mistake?

like image 221
Wauder Avatar asked Apr 07 '26 13:04

Wauder


1 Answers

Try changing you function to the following:

function addDamage(){
  var val = [
     "<tr>",
     "<td>"+nmbr+"</td>",
     "<td>"+type+"</td>",
     "<td><a href='#confirmDialog'>X</a></td>",
     "</tr>"
  ].join('');

  $("#damageList").append(val);

  nmbr++;
}

jQuery is automatically handling your first unclosed <tr> and creating <tr></tr> before appending it to #damageList. Then it appends three <td>'s to #damageList. Finally, it is discarding the closing </tr> since it doesn't know how to handle it. Concatenating the values together before appending will solve your issue.

like image 135
Brandon Boone Avatar answered Apr 10 '26 03:04

Brandon Boone