java java - 5 months ago 16
Javascript Question

Dynamically created tables - grown together

I am almost there in creating several separate html-tables dynamically in jquery. But the problem for the moment is that the tables is grown together like siamese twins.
I have a divblock in the html-file called PaymentTables and to this div I add a created class-selector paymentoptions. All this is made in a function that, after its called, create a table - exactly what I want. But if I call this function two times, the classobjects seem to be grown togehter.

How can I solve this problem so they become separate?

html

<body>

<div id="paymentTables">
</div>

</body>


javascript

window.onload = function() {


createTable();
//createTable(); call this a second time generate a second table but that seem to be grown together with the first one.


};



function createTable(){

var desc = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur";
var mytable = $('<table></table>').attr({ id: "paymentoptions_id" });
var rows = 1;
var cols = 2;
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {

switch (j) {
case 0:
$('<td valign="top"></td>').append('<input type="checkbox">').appendTo(row);
break;
case 1:
$('<td valign="top"></td>').html("text1<br><span>" + desc + "</span>").appendTo(row);
break;
}
}

}

$('#paymentTables').addClass("paymentoptions");

mytable.appendTo(".paymentoptions");
}


css

.paymentoptions {

width: 300px;
border: 1px solid black;
border-radius: 5px;
}


called once

enter image description here

called a second time

enter image description here

Could an answer be that there is close-tag missing? But where?

Answer

You do have two separate tables. The border makes them look like one table because you are placing the paymentoptions class on the surrounding <div>.

There is another issue with the HTML you are generating though. You are placing an id on the generated tables. All the generated tables will then have that same id, but id values should be unique.

Perhaps you should change this line:

var mytable = $('<table></table>').attr({ id: "paymentoptions_id" });

To this:

var mytable = $('<table></table>').addClass("paymentoptions");

And change this line:

mytable.appendTo(".paymentoptions");   

To this:

mytable.appendTo("#paymentTables");

And remove this line:

$('#paymentTables').addClass("paymentoptions");

This makes it so only the surrounding container <div> has a unique id, while each of the tables has the same paymentoptions class.

jsfiddle