I am generating a dynamic table with headers based on user input, and adding columns on click of button. While adding columns on click i want to add header to the column as well. If i click on AppendColumns button it should add column with header.
Demo:
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var Header = ["Label", "Control"];
var thead = document.createElement('thead');
table.appendChild(thead);
cellCnt = document.getElementById('txtcols').value;
for (var i = 0; i < cellCnt; i++) {
if (i % 2 == 0) {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}
else {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
}
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function AppendColumns() {
var tableCell = document.getElementById('myTable');
for (var i = 0; i < tableCell.rows.length; i++) {
var colCell = tableCell.rows[i].insertCell(tableCell.rows[i].cells.length);
colCell.width = '120';
var insertCell = (colCell, i, 'col');
}
}
<table contenteditable = "true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols"/></td>
<td><button onclick="CreateTable()">Create Table</button></td>
<td><button onclick="AppendColumns()">AppendColumn</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
try this
I think you missed to assign the value for variable cellCnt in the CreateTable() method.
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var Header = ["Label", "Control"];
var thead = document.createElement('thead');
table.appendChild(thead);
thead.id = 'tHead';
cellCnt = document.getElementById('txtcols').value;
for (var i = 0; i < cellCnt; i++) {
if (i % 2 == 0) {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}
else {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
}
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
var Header = ["Label", "Control"];
function AppendColumns() {
var tableCell = document.getElementById('myTable');
var lastIndex = tableCell.rows[0].cells.length-1;
var theader = document.getElementById('tHead');
if(lastIndex % 2 ==1){
theader.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}else{ theader.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
for (var i = 0; i < tableCell.rows.length; i++) {
var colCell = tableCell.rows[i].insertCell(tableCell.rows[i].cells.length);
colCell.width = '120';
var insertCell = (colCell, i, 'col');
}
}
<table contenteditable = "true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols"/></td>
<td><button onclick="CreateTable()">Create Table</button></td>
<td><button onclick="AppendColumns()">AppendColumn</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
Related
I need to break table headings well as table rows after 4 . Here I'm generating table dynamically from JSON string through jQuery. The table can contain maximum 16 columns, so I need to break it in 4 rows. The output should look like,
<table border=1>
<thead>
<tr>
<th>COLUMN1</th>
<th>COLUMN2</th>
<th>COLUMN3</th>
<th>COLUMN4</th>
</tr>
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>val4</td>
</tr>
</thead>
<tbody>
<tr>
<th>COLUMN5</th>
<th>COLUMN6</th>
<th>COLUMN7</th>
<th>COLUMN8</th>
</tr>
<tr>
<td>val5</td>
<td>val6</td>
<td>val7</td>
<td>val8</td>
</tr>
</tbody>
</table>
I'm using below code to generate HTML Table from JSON,
var txnJson = JSON.parse('<%=jsonObj1%>');
var tableName;
var colspan = 0;
var colHeader = [];
var rowValue = [];
for (var key in txnJson) {
tableName = key;
console.log(key);
for (var secondKey in txnJson[key]) {
console.log(secondKey + ' : ' + txnJson[key][secondKey]);
for (var thirdkey in txnJson[key][secondKey]) {
colHeader.push(thirdkey);
rowValue.push(txnJson[key][secondKey][thirdkey]);
colspan = colspan +1;
console.log(thirdkey + ' : ' + txnJson[key][secondKey][thirdkey]);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < colHeader.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.setAttribute("class", "RptHeader");
th.innerHTML = colHeader[i];
tr.appendChild(th);
}
tr = table.insertRow(-1);
for (var j = 0; j < rowValue.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = rowValue[j];
}
$('#Div<%=i%>').append(table);
I have tried using $('').html($('#Test1 td:gt(4)')).appendTo('#Test1'); but it only breaks single row. I need to iterate it after every four td.
How can I do it?
I'm able to achieve the same using below code,
`var inp = document.createElement("input");
inp.setAttribute("type","hidden");
inp.setAttribute("id","colCnt<%=i%>");
inp.setAttribute("value",colLength);
$(function () {
var colCnt = $("#colCnt<%=i%>").val();
var thLen = 3;
var tdLen = 4;
$('<tr>').html($('#Tab<%=i%> th:gt('+thLen+')')).appendTo('#Tab<%=i%>');
$('<tr>').html($('#Tab<%=i%> td:gt('+tdLen+')')).appendTo('#Tab<%=i%>');
for (var k = 0; k < colCnt; k++) {
thLen = thLen + 4;
tdLen = tdLen + 4;
$('<tr>').html($('#Tab<%=i%> th:gt('+(thLen)+')')).appendTo('#Tab<%=i%>');
$('<tr>').html($('#Tab<%=i%> td:gt('+(tdLen)+')')).appendTo('#Tab<%=i%>');
}
});
Hope, this might help someone.
I need your help,
For some reason, I can't get the data captured in my array to populate into the TD cells of my dynamically generated table:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "Request Type"
heading[1] = "Group A"
heading[2] = "Groub B"
heading[3] = "Group C"
heading[4] = "Total"
var stock = new Array()
stock[0] = new Array("Cars", "88.625", "85.50", "85.81", "987")
stock[1] = new Array("Veggies", "88.625", "85.50", "85.81", "988")
stock[2] = new Array("Colors", "88.625", "85.50", "85.81", "989")
stock[3] = new Array("Numbers", "88.625", "85.50", "85.81", "990")
stock[4] = new Array("Requests", "88.625", "85.50", "85.81", "991")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < stock.length; i++) {
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td)
}
}
myTableDiv.appendChild(table)
}
</script>
</head>
<div id="metric_results">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
</div>
</body>
</html>
Change:
var tr = document.createElement('TR'); // this should be inside the first loop
tableBody.appendChild(tr); // this should be just before the first loop is over
for (i=0; i<stock.length; i++) {
for (j=0; j<stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td) // this should be tr.appendChild(td)
}
}
to this:
for (i = 0; i < stock.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
Fiddle
Have Javascript (not JQuery) move table row (TR) up or down, not just the block of TD Cells.
Add 2 Rows, then you notice that it just moves the cell down or up when you click the up or down button, but not the entire rows color. The information looks like it all gets moved.
I am using javascript only, so JQuery wont work.
Codepen of working code
https://codepen.io/soljohnston777/pen/zYBrMxL
var activeRow = 0;
function setActiveRow(el) {
var rows = document.getElementById('movingTable').rows;
for (var i = 1; i < rows.length; i++) {
if (rows[i] == el) activeRow = i;
}
}
function moveActiveRow(move) {
var rows = document.getElementById('movingTable').rows;
var oldRow = rows[activeRow].innerHTML;
var newRow = rows[activeRow + move].innerHTML;
rows[activeRow].innerHTML = newRow;
rows[activeRow + move].innerHTML = oldRow;
setActiveRow(rows[activeRow + move]);
}
function moveRow(cell, move) {
// alert("Row index is: " + cell.name);
setActiveRow(cell.parentNode);
moveActiveRow(move);
}
function doSubmit() {
var rows = document.getElementById('movingTable').rows;
var ret = new Array();
for (var i = 0; i < rows.length; i++) {
ret[ret.length] = rows[i].getElementsByTagName('td')[0].innerHTML;
}
return ret.join('|');
}
function AddSection() {
var txtName = document.getElementById("txtName");
AddRow(txtName.value, "1");
txtName.value = "";
};
function AddLesson() {
var txtName = document.getElementById("txtName");
AddRow(txtName.value, "2");
txtName.value = "";
};
function AddRow(name, section) {
var table = document.getElementById("movingTable");
// 1 section , 2 lesson
if (section == "1") {
var row = table.insertRow(-1);
var input1 = document.createElement('input');
input1.type = "hidden";
var input2 = document.createElement('input');
input2.type = "text";
input2.setAttribute("value", name);
input2.setAttribute("name", "section[]");
input2.setAttribute("style", "background-color: #5cffde;");
var inputhidden1 = document.createElement('input');
inputhidden1.type = "hidden";
inputhidden1.setAttribute("name", "section[]");
var inputhidden2 = document.createElement('input');
inputhidden2.type = "hidden";
var input3 = document.createElement('input');
input3.type = "button";
input3.value = "Up";
input3.setAttribute("onclick", "moveRow(this, -1);");
var input4 = document.createElement('input');
input4.type = "button";
input4.value = "Down";
input4.setAttribute("onclick", "moveRow(this, 1);");
var input5 = document.createElement('input');
input5.type = "button";
input5.value = "Remove";
input5.setAttribute("onclick", "Remove(this);");
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
cell1.appendChild(input1);
cell2.appendChild(input2);
cell2.appendChild(inputhidden1);
cell2.appendChild(inputhidden2);
cell3.appendChild(input3);
cell4.appendChild(input4);
cell5.appendChild(input5);
inputhidden1 = "";
inputhidden2 = "";
}
if (section == "2") {
var row = table.insertRow(-1);
var input1 = document.createElement('input');
input1.type = "hidden";
var input2 = document.createElement('input');
input2.type = "text";
input2.setAttribute("value", name);
input2.setAttribute("name", "Lesson[]");
var input3 = document.createElement('input');
input3.type = "button";
input3.value = "Up";
input3.setAttribute("onclick", "moveRow(this, -1);");
var input4 = document.createElement('input');
input4.type = "button";
input4.value = "Down";
input4.setAttribute("onclick", "moveRow(this, 1);");
var input5 = document.createElement('input');
input5.type = "button";
input5.value = "Remove";
input5.setAttribute("onclick", "Remove(this);");
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var cell3 = row.insertCell(-1);
var cell4 = row.insertCell(-1);
var cell5 = row.insertCell(-1);
cell1.appendChild(input1);
cell2.appendChild(input2);
cell3.appendChild(input3);
cell4.appendChild(input4);
cell5.appendChild(input5);
}
var colors = new Array('#ffffff', '#dddddd', '#aaaaaa', '#888888');
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
doMultiple(rows[i], i, rows[i].className);
}
function doMultiple(row, i, s) {
if (section == "1" || s == "sections") {
row.className = "sections";
} else {
row.style.backgroundColor = colors[i % colors.length];
}
}
}
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = button.parentNode.parentNode;
var name = row.getElementsByTagName("TD")[0].innerHTML;
if (confirm("Do you want to delete this?")) {
//Get the reference of the Table.
var table = document.getElementById("movingTable");
//Delete the Table row using it's Index.
table.deleteRow(row.rowIndex);
}
};
table {
border-collapse: collapse;
table-layout: fixed;
width: 100%;
}
table td {
border: solid 1px #e7e7e7;
width: 100px;
word-wrap: break-word;
}
.sections {
background-color: #5cffde;
}
<table border="1" cellspacing="0" cellpadding="0" id="mTable">
<thead>
<tr>
<td>Section?</td>
<td>Section/Lesson Name</td>
<td>Move Up</td>
<td>Move Down</td>
<td>Delete</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table border="1" cellspacing="0" cellpadding="0" id="movingTable">
</table>
<table width="100" border="1" cellspacing="0" cellpadding="0" id="">
<tfoot>
<td></td>
<td><input type="text" id="txtName" /></td>
<td></td>
<td><input type="button" onclick="AddSection()" value="Add Section" /></td>
<td><input type="button" onclick="AddLesson()" value="Add Lesson" /></td>
</tfoot>
</table>
I have a table which i am dynamically generating based on user input. I am trying to insert a label text into table cell on button click. onclick of button a label text of a demo method should be inserted into table cells. Can someone suggest me how can i do this?
Thanks.
Creating Table:
function CreateTable(){
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById('myDynamicTable');
var table = document.createElement('table');
table.setAttribute("contenteditable", "true");
table.border = "1";
table.id = "myTable";
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Button:
<asp:Button ID="button1" Text="button" runat="server" OnClick="demo" />
C# code:
public void demo()
{
TableCell tcell = new TableCell();
RadLabel rlbl = new RadLabel();
rlbl.Text = "test";
tcell.Controls.Add(rlbl);
}
protected void demo(object sender, EventArgs e)
{
demo();
}
To give you a start using Javascript, you can use below code as a starting point.
window.onload=function(){
CreateTable();
}
function CreateTable(){
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById('myDynamicTable');
var table = document.createElement('table');
table.setAttribute("contenteditable", "true");
table.border = "1";
table.id = "myTable";
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
rowCnt = 3; //document.getElementById('txtrows').value;
cellCnt =2; //document.getElementById('txtcols').value;
for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function demo(){
var myTable=document.getElementById('myTable');
var cell=myTable.rows[0].cells[1];
var label = document.createElement('label');
label.id="lbl-"+cell.cellIndex;
label.innerText="This is label text";
cell.appendChild(label);
}
<input type="button" onclick="demo()" value="Create Label" />
<div id="myDynamicTable"></div>
I am trying to work out how to save and load data from tables using cookies.
I have been able to save the data to the cookie, but the load function isn't working.
Any idea on how I can make this work?
Basically, I want the cookie to save the data in the table using the "save" button. Then you can mess about with the table and the "load" button will bring it back to how it looked when it was saved.
<html>
<head>
</head>
<body>
<table style="width:100%" id="myTable">
<tr>
<th>Col 1</th>
<th >Col 2</th>
<th >Col 3</th>
<th>Col 4</th>
</tr>
<tr>
<td contenteditable="true" id="left">-</td>
<td contenteditable="true" id="left">-</td>
<td contenteditable="true">-</td>
<td>-</td>
</tr>
</table>
<p id = "paragraph">
</p>
<button type= "submit" class="button" onclick="addRow()">
Add Row
</button>
<button type= "submit" class="button" onclick="addCol()">
Add Col
</button>
<button type= "submit" class="button" onclick="saveTable()">
Save
</button>
<button type= "submit" class="button" onclick="LoadTable()">
Load
</button>
<script>
function addRow()
{
var table = document.getElementById("myTable");
var endOfRows = table.rows.length; // length of rows
var row = table.insertRow(endOfRows);
var endOfCols = table.rows[0].cells.length; // end of cols
for(var i = 0; i< endOfCols; i++)
{
var cell = row.insertCell(i);
cell.innerHTML = "-";
if( i == endOfCols-1)
{
cell.contentEditable = "false";
}
else
{
cell.contentEditable = "true";
}
if(i > 1)
{
cell.style.textAlign = "right";
}
else
{
cell.style.textAlign = "left";
}
}
}
function addCol()
{
var table = document.getElementById("myTable");
var rowLength = table.rows.length;
var endOfCol = table.rows[0].cells.length;
for(var i = 0; i < rowLength; i++)
{
var firstRow = document.getElementById("myTable").rows[i];
var cell = firstRow.insertCell(endOfCol-1);
cell.contentEditable = "true"
if(i == 0)
{
cell.innerHTML = "-";
cell.style.textAlign = "center";
cell.style.backgroundColor = "black";
cell.style.color = "white";
cell.style.fontWeight = "600";
}
else
{
cell.innerHTML = "-";
}
}
}
function saveTable()
{
var table = document.getElementById("myTable");
var noOfRows = table.rows[0].cells.length; // amount of cols
var noOfCols = table.rows.length;
var data = '';
for(var i = 1; i < table.rows.length; i++)
{
for(var j = 0; j < table.rows[0].cells.length-1; j++)
{
data += table.rows[i].cells[j].innerHTML + ",";
}
}
setCookie("data", data, noOfCols, noOfRows, 60);
alert("Cookie Saved");
}
function setCookie(cname, cvalue, noOfRows, noOfCols, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue +";" + expires + ";path=/";
}
function LoadTable()
{
var table = document.getElementById("myTable");
var rowLength = table.rows.length;
var endOfCol = table.rows[0].cells.length;
var data = getCookie("data");
var array = data.split(',');
var count = 0;
for(var i =1;i<rowLength;i++)
{
for(var j = 0; j < endOfCol-1; j++)
{
table.rows[i].cells[j].innerHTML = array[count];
count++;
}
}
}
function getCookie(cname)
{
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) == ' ')
{
c = c.substring(1);
}
if (c.indexOf(name) == 0)
{
return c.substring(name.length, c.length);
}
}
return "";
}
PS. I need to do this where the last column is adding up the numbers from the other columns on that row, so we want to skip this column when adding the data, and also not save whatever is in this cell.