problem counting the rows from dynamic table creation - javascript

I have created a dynamic table without any problem. But I am getting the wrong row numbers. Also when I remove a row I need to show the correct numbers in ascending order.
var myHead = new Array();
myHead = ['Title1','Title2', 'Title3',''];
function createTable() {
var myTable = document.createElement('table');
myTable.setAttribute('id', 'myTable');
var tr = myTable.insertRow(-1);
for (var h = 0; h < myHead.length; h++) {
var th = document.createElement('th');
th.innerHTML = myHead[h];
tr.appendChild(th);
}
var div = document.getElementById('main_Div');
div.appendChild(myTable);
}
function addRow() {
var myTab = document.getElementById('myTable');
var rowCnt = myTab.rows.length;
var tr = myTab.insertRow(rowCnt);
tr = myTab.insertRow(rowCnt);
var No = "Row_"+rowCnt;
for (var c = 0; c < myHead.length; c++) {
var td = document.createElement('td');
td = tr.insertCell(c);
if (c == 0) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', No);
ele.setAttribute('readonly', true);
ele.setAttribute('name', 'No');
td.appendChild(ele);
}
else if (c == 1) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
ele.setAttribute('name', 'T_Name');
ele.setAttribute('id', 'T_Name');
td.appendChild(ele);
}
else if (c == 2) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
else if (c == 3) {
var button = document.createElement('input');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
}
}
function removeRow(button) {
var myTab = document.getElementById('myTable');
myTab.deleteRow(button.parentNode.parentNode.rowIndex);
}
<head>
<title>Dynamic table</title>
</head>
<body onload="createTable()">
<input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
<div id="main_Div"></div>
</body>
I have started to use JavaScript recently and having trouble working on in my project.
Please anyone help me? Thank you so much in advance.

If you want rows renumbered after some action you need to re-number every row after the one you have removed. One way to do that is to map over every row and update the values of your inputs.
var myHead = new Array();
myHead = ['Title1','Title2', 'Title3',''];
function createTable() {
var myTable = document.createElement('table');
myTable.setAttribute('id', 'myTable');
var tr = myTable.insertRow(-1);
for (var h = 0; h < myHead.length; h++) {
var th = document.createElement('th');
th.innerHTML = myHead[h];
tr.appendChild(th);
}
var div = document.getElementById('main_Div');
div.appendChild(myTable);
}
function addRow() {
var myTab = document.getElementById('myTable');
var rowCnt = myTab.rows.length;
var tr = myTab.insertRow(rowCnt);
// tr = myTab.insertRow(rowCnt);
var No = "Row_"+rowCnt;
for (var c = 0; c < myHead.length; c++) {
var td = document.createElement('td');
td = tr.insertCell(c);
if (c == 0) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', No);
ele.setAttribute('readonly', true);
ele.setAttribute('name', 'No');
td.appendChild(ele);
}
else if (c == 1) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
ele.setAttribute('name', 'T_Name');
ele.setAttribute('id', 'T_Name');
td.appendChild(ele);
}
else if (c == 2) {
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
else if (c == 3) {
var button = document.createElement('input');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
}
}
function removeRow(button) {
var myTab = document.getElementById('myTable');
myTab.deleteRow(button.parentNode.parentNode.rowIndex);
// Use map to rebuild input values
[].slice.call(myTab.rows).map(
function (item,index) {
if (item.firstChild.firstChild.nodeType == 1) {
item.firstChild.firstChild.value = "Row_" + index
};
return true;
});
}
<head>
<title>Dynamic table</title>
</head>
<body onload="createTable()">
<input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
<div id="main_Div"></div>
</body>

Related

Set type text inside cell javascript

I want to type text inside the cell but I tried to set attribute with td but it doesn't work. Please help me how can I set attribute to type text in the cell. Thank you for your help!
function addTable() {
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
You need to create an input element and then append that to td:
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns", 1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', 'text');
td.appendChild(input);
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
<div id="myDynamicTable">
</div>
You can use contenteditable attribute: td.contenteditable = 'true';.
Depending on how you want to use this value, you might also insert an input element.
You are perhaps looking for contentEditable?
function addTable() {
const rn = +window.prompt("Input number of rows", 1);
const cn = +window.prompt("Input number of columns", 1);
const myTableDiv = document.getElementById("myDynamicTable");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (let i = 0; i < rn; i++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (let j = 0; j < cn; j++) {
var td = document.createElement('td');
td.width = '75';
td.contentEditable = true;
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>
if you want to operate on tables, use corrects javascript instructions ...
const
DynTb = document.getElementById('myDynamicTable')
rn = +window.prompt("Input number of rows", 1)
, cn = +window.prompt("Input number of columns", 1)
;
if( isNaN(rn) || isNaN(cn))
throw 'bad integer input value (s)'
const myTable = addTable(DynTb, rn, cn )
function addTable(tDiv, rn, cn)
{
let
tab = tDiv.appendChild( document.createElement('table') )
, tBy = tab.createTBody()
;
for(let r=0;r<rn;++r)
{
let row = tBy.insertRow()
for(let c=0;c<cn;++c)
{
row.insertCell().innerHTML =
`<input type="text" placeHolder="${r}-${c}">`
} }
return tab
}
table {
border-collapse : collapse;
margin : 2em 1em;
}
td {
padding : .2em;
border : 1px solid darkblue;
}
input {
width : 5em;
}
<div id="myDynamicTable"></div>

Displaying javascript data in html after retrieving it from mysql [duplicate]

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 Cell (TD)

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>

How can i insert a label text in a table cell

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>

How to add onClick function to this code

I am trying to add an onclick function to this table. So when I click on the cell it will change color from red to blue.
Relevant code below:
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<ruudud.value; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<ruudud.value; j++){
var td = document.createElement('TD');
td.width='50';
td.height='50';
td.style.backgroundColor="red";
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
There is many ways to do this as the below :
1 - In for loop
<div id="myDynamicTable"></div>
<script type="text/javascript">
addTable();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3 ; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 2; j++) {
var td = document.createElement('TD');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
//************************************************
td.setAttribute("onclick", "yourFun(this)");
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function yourFun(tdObj) {
tdObj.style.backgroundColor = "green";
}
2 - By Function :
<div id="myDynamicTable"></div>
<script type="text/javascript">
addTable();
setFunction();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3 ; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 2; j++) {
var td = document.createElement('TD');
td.width = '50';
td.height = '50';
td.style.backgroundColor = "red";
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function setFunction() {
var myTableDiv = document.getElementById("myDynamicTable");
var tds = myTableDiv.getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
tds[i].setAttribute("onclick", "yourFun(this)");
}
}
function yourFun(tdObj) {
tdObj.style.backgroundColor = "green";
}
3- Or You can use Event Delegation see this http://davidwalsh.name/event-delegate
You can do it by setting the onclick attribute for each td in your for loop which calls a corresponding function to handle a class change. The colors can be defined in your css for the two classes.
// for loop addition
td.setAttribute('class', 'bgRed');
// and
td.setAttribute('onclick', chgColor(this));
// or
td.onclick(function(this) {return function() {chgColor(this);};})(this);
// Function for changing td background class/color
function chgColor(td){
td.className == "bgRed" ? td.className = "bgBlue" : td.className = "bgRed";
}
You can directly add the event listener on the table, and in the callback you can check the event source and act accordingly. The event source would be a node so if you want to hold any specific data, you can keep attributes and read them on event.

Categories

Resources