Create HTML Table dynamically with the JSON Dataset available using Javascript
Here is the Code to achieve this:-function CreateTable(data) {
var parentDivTable = document.getElementById('tblAllEmployee');
var table = document.createElement('table');
table.setAttribute('border', '1');
table.setAttribute('class', 'CSSTableGenerator');
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
var header = ['Employee Id', 'Employee Name', 'Contact Number'];
var i = 0;
for (i = 0; i < header.length; i++)
{
td = document.createElement('th');
td.innerHTML = header[i];
tr.appendChild(td);
}
thead.appendChild(tr);
for (i = 0; i < data.length; i++)
{
tdEmpId = document.createElement('td');
tdEmpId.innerHTML = data[i].EmployeeId;
tdEmpName = document.createElement('td');
tdEmpName.innerHTML = data[i].Name;
tdContactNumber = document.createElement('td');
tdContactNumber.innerHTML = data[i].ContactNumber;
tr = document.createElement('tr');
tr.appendChild(tdEmpId);
tr.appendChild(tdEmpName);
tr.appendChild(tdContactNumber);
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
while (parentDivTable.hasChildNodes())
{
parentDivTable.removeChild(parentDivTable.firstChild);
}
parentDivTable.appendChild(table);
}
Here "data" is the JSON dataset or arrays, "tblAllEmployee" is the Div Id under which the HTML table will be created, "CSSTableGenerator" is the class for the table.
No comments:
Post a Comment