Reputation: 33
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?
Upvotes: 3
Views: 45
Reputation: 144679
DOM doesn't work that way. You can't append opening/closing tags separately. You should pass a full string representation of an element. What happens is:
$("#damageList")
.append(trA, // append a TR, since `<tr>` can be parsed as an element
td1, // append a TD
td2, // append a TD
td3, // append a TD
trB // append a closing `</tr>` tag, silently fails
);
You can concatenate the strings and then pass it to jQuery.
$("#damageList").append(trA + td1 + td2 + td3 + trB);
Also note that you should wrap the rows with a tbody
element and append the generated rows to it:
$("#damageList tbody").append(...)
Upvotes: 1
Reputation: 16472
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.
Upvotes: 2