java java - 1 year ago 54
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?



<div id="paymentTables">



window.onload = function() {

//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);
case 1:
$('<td valign="top"></td>').html("text1<br><span>" + desc + "</span>").appendTo(row);





.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 Source

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:


To this:


And remove this line:


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