0

I want to create html table dynamically and number of table will be depend upon the response I am getting in array. New table should be created after every 6 elements and table header will be array elements itself. Expected output is-

-------------------------------------
| th1 | th2 | th3 | th4 | th5 | th6 |
-------------------------------------
|     |     |     |     |     |     |
-------------------------------------

code for generating table is as below in which consoles are printing properly but elements are not getting create and not getting any error too.

'<div id="findingDiv">';

    for(var i=0;i<tables;i++){
         console.log('i-',i);                               
        '<table class="table table-bordered" style="margin-top: 10px; border:1px solid black; border-collapse : collapse;font-size: 30px;">'+
            '<thead>'+
                '<tr>';

                for(var k=0;k<6;k++){   

                    '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);"> historyTable[k] </th>';
                    console.log('k-',k);
                }

       '</table> \n';                               
    }

Can anybody help me??

I have checked previous solutions which did not worked. How to clone() a element n times? How to use loop in Jquery to add table multiple times into div Create a table dynamically using for loop in .html()

1

1 Answer 1

0

You can use jQuery .append() method to add HTML table to your DIV dynamicaly in for loop.

Working fiddle

You can use below code.

Below DIV in html:

<div id="findingDiv">
</div>

Code in jquery. I used jQuery .ready() method to create it on page load:

$(document).ready(function () {
    var tables = ['th1','th2','th3','th4','th5','th6']

    for(var i=0;i<tables.length;i++){
    var content = "<table><thead><tr>";
        for(var k=0;k<6;k++)
        {
            content += '<th id="header" style="color:black; font-size: 12px; border:1px solid black; text-align:center;border-color: rgb(166, 166, 166);">'+tables[k]+' </th>';                    
        }
        content += "</tr></thead></table><br/>";
        $('#findingDiv').append(content);
    }
 });

I just added the th, same way you can add tr as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes thnx..But it is working when div findingDiv is defined in html code. I can not create div in html I need to create it dynamically on click event. And in that case this doesn't work.
Well, in that case, you can create DIV as well in jquery. But you need to use .append(content) on any element, may be a body. Because you can't directly inject element to the DOM.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.