balouchi balouchi - 7 months ago 19
HTML Question

How to create a dynamic table in jQuery?

I want to create a dynamic table in jQuery. But my code creates a table for each of my element.

var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content = "<table>" + "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";


Which part of my code is wrong?

Answer

as you were adding table in for loop, so it was creating table for each item.Try this:

var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
content ="<table>"
 for (var i = 0; i < spl.length; i++) {
     part = spl[i].split(':');
     content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
     spl2 = content;
 }
content += "</table>"

// you can also assign spl2 = content; over here.
    var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
        spl2
        + "</span><br/>" +
        +  "</div>";
Comments