Skip to content

Instantly share code, notes, and snippets.

@jineeshjohn
Last active December 5, 2018 18:59
Show Gist options
  • Save jineeshjohn/2044414 to your computer and use it in GitHub Desktop.
Save jineeshjohn/2044414 to your computer and use it in GitHub Desktop.
Dynamic html table rows and column creation with jQuery
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<style>
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
</style>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rowcount").val());
var cols = new Number($("#columncount").val());
var tr = [];
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++) {
$('<td></td>').text("text1").appendTo(row);
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#box");
}
</script>
Row Count:<input type="text" id="rowcount" />
Column Count:<input type="text" id="columncount" />
<input type="button" onclick="createTable();" value="Create Table" />
<div id="box">
</div>
@Nishanthbob
Copy link

If i want to change the height of the row where can i change. i tried but not working
var row = $('').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
Can any one help me in that.
Revert back to me at [email protected]

@hemanthvelamuri
Copy link

table tr{
height:100px;
}

@nis92009
Copy link

How to add column headings

@antonycs
Copy link

antonycs commented Aug 30, 2016

Table with column heading

function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable",class:"table table-hover"});
    var rows = new Number($("#rowcount").val());
    var cols = new Number($("#columncount").val());
    var tr = [];

    for (var i = 0; i <= rows; i++) {
        var row = $('<tr></tr>').attr({ class: ["class1"].join(' ') }).appendTo(mytable);
    if (i==0) {
      for (var j = 0; j < cols; j++) {
            $('<th></th>').text("text1").attr({class:["info"]}).appendTo(row);
        }
    }else {
        for (var j = 0; j < cols; j++) {
            $('<td></td>').text("text1").appendTo(row);
        }
}
    }

    mytable.appendTo("#box");
}

@kingofnull
Copy link

kingofnull commented Mar 13, 2017

I wrote rather good function that can generate vertical and horizontal tables:

function generateTable(rowsData, titles, type, _class) {
    var $table = $("<table>").addClass(_class);
    var $tbody = $("<tbody>").appendTo($table);

    
    if (type == 2) {//vertical table
        if (rowsData.length !== titles.length) {
            console.error('rows and data rows count doesent match');
            return false;
        }
        titles.forEach(function (title, index) {
            var $tr = $("<tr>");
            $("<th>").html(title).appendTo($tr);
            var rows = rowsData[index];
            rows.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });
        
    } else if (type == 1) {//horsantal table 
        var valid = true;
        rowsData.forEach(function (row) {
            if (!row) {
                valid = false;
                return;
            }

            if (row.length !== titles.length) {
                valid = false;
                return;
            }
        });

        if (!valid) {
            console.error('rows and data rows count doesent match');
            return false;
        }

        var $tr = $("<tr>");
        titles.forEach(function (title, index) {
            $("<th>").html(title).appendTo($tr);
        });
        $tr.appendTo($tbody);

        rowsData.forEach(function (row, index) {
            var $tr = $("<tr>");
            row.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });
    }

    return $table;
}

usage example:

var title = [
	'مساحت موجود',
	'مساحت باقیمانده',
	'مساحت در طرح'
];

var rows = [
	[number_format(data.source.area,2)],
	[number_format(data.intersection.area,2)],
	[number_format(data.deference.area,2)]
];

var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");

$ft.appendTo( GroupAnalyse.$results );

var title = [
	'جهت',
	'اندازه قبلی',
	'اندازه فعلی',
	'وضعیت',
	'میزان عقب نشینی',
];

var rows = data.edgesData.map(function (r) {
	return [
		r.directionText,
		r.lineLength,
		r.newLineLength,
		r.stateText,
		r.lineLengthDifference
	];
});


var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");

$et.appendTo( GroupAnalyse.$results );

$('<hr/>').appendTo( GroupAnalyse.$results );

numberformat function round the given number and GroupAnalyse.$results is my jquery instance (like GroupAnalyse.$results=$('#myTableWrapper')) of my target html element to put my table

@ansarisufiyan777
Copy link

function createTableDynamically(){
var table = "

";
for (var key in Object.keys(data[0])) {
table += "";
}
table += "";
for (var position in data) {
table += "<tr company-id='" + data[position]['PublicCompanyId'] + "'>"
for (var key in data[position]) {
table += "";
}
table += "";
}
table += "
" + Object.keys(data[0])[key] + "
" + data[position][key] + "
";
$("#DIVID").empty();
$("#DIVID").html(table);

}

your JSONshould look like this

[ { "id":28, "Title":"Sweden" }, { "id":56, "Title":"USA" }, { "id":89, "Title":"England" } ]

@abhishek-sisodiya
Copy link

i'm generating table dynamically using jquery.
http://jsfiddle.net/qvh7yeut/

now what im trying is to remove selected option in other dropdowns

can anybody help?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment