JavaScript Type Error 'childnodes' undefined - javascript

Need to Dynamically Add/Remove rows in HTML table using JavaScript getting a type error.
Type Error: cannot read property 'childNodes' of undefined?
Catches this exception in run time during deleteRow function execution.
On pressing Add Row, a dynamic row will be created and added in the table. And on selecting the checkbox and pressing Delete Row, the row will be removed.
Following is the source.
<html>
<head>
<script>
var b = new Array();
var entryListCounter = 0;
var counter = 0;
function insertEntry(f) {
var test = 0;
//local array collects input values
var a = new Array();
a[0] = f.ticker.value;
a[1] = f.cusip.value;
a[2] = f.quantity.value;
//store local array in entry list array
b[entryListCounter] = a;
entryListCounter++;
if (a[0] == "" && a[1] == "" || a[2] == "") {
console.log("val not filled");
}
else if(a[0].length > 0 && a[1].length > 0){
console.log("only fill one");
}
else {
var table = document.getElementById("manualEntryInputTable");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var t1 = document.createElement("input");
t1.id = "t" + counter;
cell1.appendChild(t1);
var cell2 = row.insertCell(1);
var t2 = document.createElement("input");
t2.id = "c" + counter;
cell2.appendChild(t2);
var cell3 = row.insertCell(2);
var t3 = document.createElement("input");
t3.id = "q" + counter;
t3.style = "text-align:right";
cell3.appendChild(t3);
var cell4 = row.insertCell(3);
var t4 = document.createElement("input");
t4.type = "checkbox";
t4.name = "chkbox";
cell4.appendChild(t4);
f.quantity.value = "";
f.cusip.value = "";
f.ticker.value = "";
}
}
function deleteRow(e) {
try {
var table = document.getElementById("manualEntryInputTable");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[3].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<table id="manualEntryInputTable">
<tr>
<td><b>T</b></td>
<td><b>C</b></td>
<td><b>Q</b></td>
</tr>
<tr>
<td class="label"><input size="" type="text" name="ticker"
value="" ></td>
<td class="label"><input size="" type="text" name="cusip"
value=""></td>
<td class="label"><input size="" type="text" name="quantity"
style="text-align: right;" value="">
</td>
<td><input type="button" onClick="insertEntry(this.form)" value="Add"/>
</td>
<td><input type="button" onClick="deleteRow(this.form)" value="Delete"/>
</td>
</tr>
</table>
</form>
</body>
</html>

By looking at the conditional checking for null, I would rewrite it like this:
var chkbox = row.cells[3].childNodes.length ? row.cells[3].childNodes[0] : null;
That should avoid the error being thrown, but might not get the row deleted if the cell with index 3 doesn't exist. Consider checking the value of the right cell index row.cells[YOUR_CELL_INDEX_HERE].childNodes[0]

I am not entirely sure what you are trying to do, but the reason for exception is that you are trying to access the element which doesn't exists.
This line is giving the error row.cells[3].childNodes[0] since you do not have row.cell[3] property. The row.Cells has length 3 but since the index starts from 0, you can refer to the last element using row.cells[2] You get undefined and hence row.cells[3].childNodes[0] method doesn't work.
change it to row.cells[2].childNodes[0]
<html>
<head>
<script>
var b = new Array();
var entryListCounter = 0;
var counter = 0;
function insertEntry(f) {
var test = 0;
//local array collects input values
var a = new Array();
a[0] = f.ticker.value;
a[1] = f.cusip.value;
a[2] = f.quantity.value;
//store local array in entry list array
b[entryListCounter] = a;
entryListCounter++;
if (a[0] == "" && a[1] == "" || a[2] == "") {
console.log("val not filled");
}
else if(a[0].length > 0 && a[1].length > 0){
console.log("only fill one");
}
else {
var table = document.getElementById("manualEntryInputTable");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var t1 = document.createElement("input");
t1.id = "t" + counter;
cell1.appendChild(t1);
var cell2 = row.insertCell(1);
var t2 = document.createElement("input");
t2.id = "c" + counter;
cell2.appendChild(t2);
var cell3 = row.insertCell(2);
var t3 = document.createElement("input");
t3.id = "q" + counter;
t3.style = "text-align:right";
cell3.appendChild(t3);
var cell4 = row.insertCell(3);
var t4 = document.createElement("input");
t4.type = "checkbox";
t4.name = "chkbox";
cell4.appendChild(t4);
f.quantity.value = "";
f.cusip.value = "";
f.ticker.value = "";
}
}
function deleteRow(e) {
try {
var table = document.getElementById("manualEntryInputTable");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[2].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<table id="manualEntryInputTable">
<tr>
<td><b>T</b></td>
<td><b>C</b></td>
<td><b>Q</b></td>
</tr>
<tr>
<td class="label"><input size="" type="text" name="ticker"
value="" ></td>
<td class="label"><input size="" type="text" name="cusip"
value=""></td>
<td class="label"><input size="" type="text" name="quantity"
style="text-align: right;" value="">
</td>
<td><input type="button" onClick="insertEntry(this.form)" value="Add"/>
</td>
<td><input type="button" onClick="deleteRow(this.form)" value="Delete"/>
</td>
</tr>
</table>
</form>
</body>
</html>

Related

How do I get html multiple row table data to Javascript

HTML table
<table id="dataTable" border="1px" style="width:355px; BORDER-COLLAPSE:collapse">
<tr>
<td id="0" align="center"></td>
<td id="1" align="center">Name</td>
<td id="2" align="center">Designation</td>
<td id="3" align="center">PAN</td>
<td id="4" align="center">Address</td>
</tr>
<tr>
<td><input type="checkbox" name="chk" id ="chk" size="6"/></td>
<td><input type="text" name="txtRow1" id="txtRow1" size="8"/></td>
<td><input type="text" name="txtRow2" id="txtRow2" size="8"/></td>
<td><input type="text" name="txtRow3" id="txtRow3" size="8"/></td>
<td><input type="text" name="txtRow4" id="txtRow4" size="8"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRowTable('dataTable')" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRowTable('dataTable')" /></td>
</tr>
</table>
After entering data into HTML table, I want to get that data to javascript so that I could save it in the database. The HTML table contains multiple rows and four columns. User can add rows if they want to add column to enter data. I want to get all the column data to the javascript. How do I do that..Kindly help me
My HTML Code:
function addRowTable(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 10) {
alert("Maximum 10 rows allowed");
return false;
}
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
element1.size = 8;
/*var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;*/
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
element2.size = 8;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
element3.size = 8;
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
cell4.appendChild(element4);
element4.size = 8;
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtbox[]";
cell5.appendChild(element5);
element5.size = 8;
}
function deleteRowTable(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
/*alert(e);*/
}
}
My javascript code to add and delete table rows:
Now after table columns are filled, i want to get that data to javascript.I tried to do like below. But it is not working.I am getting null values.I am not getting the actual values.
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++)
{
var Name = $("dataTable").find("tr").eq(i).find("td").eq(0).text();
var Designation = $("dataTable").find("tr").eq(i).find("td").eq(1).text();
var PAN = $("dataTable").find("tr").eq(i).find("td").eq(2).text();
var Address = $("dataTable").find("tr").eq(i).find("td").eq(3).text();
}
Kindly let me know what am I doing wrong and what should I do.
Thank You!
The data of an HTML table can be stored in a JS array, it's easier than putting the data into variables (which are storing the last row only).
var rows = table.rows,
len = rows.length,
data = [],
cells;
for (var n = 1; n < len; n++) {
cells = rows[n].cells;
data.push([
cells[0].firstElementChild.checked,
cells[1].firstElementChild.value,
cells[2].firstElementChild.value,
cells[3].firstElementChild.value,
cells[4].firstElementChild.value
]);
}
Now it's easy to read the values from data array when needed.
You are on the right way, but pay attention to some details:
In your solution you select the 'td' not the input inside it.
If you use an input you cannot get the innterText by calling .text() instead you want to use the .val() method to receive the
value
Name your inputs consistently. In your first row you name them "txtRow1"-"textRow4" ... but when you add new rows you name them
"txtbox[]": First of all i think you mean txtCol not txtRow ... just think about it. Second you if you want to group your inputs by column then append the "[]" brackets to the names that belong together like so "txtCol1[]" - "txtCol4[]"
I have put it all together for you:
function addRowTable(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 10) {
alert("Maximum 10 rows allowed");
return false;
}
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
element1.size = 8;
/*var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;*/
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtCol1[]";
cell2.appendChild(element2);
element2.size = 8;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtCol2[]";
cell3.appendChild(element3);
element3.size = 8;
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtCol3[]";
cell4.appendChild(element4);
element4.size = 8;
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtCol4[]";
cell5.appendChild(element5);
element5.size = 8;
}
function deleteRowTable(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
/*alert(e);*/
}
}
function readData(tableID){
var rowCount = $(tableID + ' tr').length;
var results = [];
for (var i = 1; i < rowCount; i++)
{
results.push({
Name: $(tableID).find('tr').eq(i).find('[name="txtCol1[]"]').val(),
Designation: $(tableID).find('tr').eq(i).find('[name="txtCol2[]"]').val(),
PAN: $(tableID).find('tr').eq(i).find('[name="txtCol3[]"]').val(),
Address: $(tableID).find('tr').eq(i).find('[name="txtCol4[]"]').val(),
});
}
console.log(results);
return results;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="dataTable" border="1px" style="width:355px; BORDER-COLLAPSE:collapse">
<tr>
<td id="0" align="center"></td>
<td id="1" align="center">Name</td>
<td id="2" align="center">Designation</td>
<td id="3" align="center">PAN</td>
<td id="4" align="center">Address</td>
</tr>
<tr>
<td><input type="checkbox" name="chkbox[]" id="chk" size="6" /></td>
<td><input type="text" name="txtCol1[]" id="txtCol1" size="8" /></td>
<td><input type="text" name="txtCol2[]" id="txtCol2" size="8" /></td>
<td><input type="text" name="txtCol3[]" id="txtCol3" size="8" /></td>
<td><input type="text" name="txtCol4[]" id="txtCol4" size="8" /></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRowTable('dataTable')" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRowTable('dataTable')" /></td>
<td><input type="button" value="Read Data" onclick="readData('#dataTable')" /></td>
</tr>
</table>

Dynamic add/remove rows and auto calculating totals- Problem with calculation when deleting inner rows

So I have pieced together a script I want to use to create invoices. It adds "Invoice Items" as a table row which includes checkbox, Quantity, Item, Unit Cost, and Price.
You can then check item, or use check-all option (Upper Left) to remove rows. As well as that it auto calculates row totals as well as a Sub Total for the whole "Invoice". As long as you remain linear, add items as will without removing them (unless removing all of them) it adds up fine. The issue I am having is if you remove any items in the middle it wont calculate total anymore.
Here is a jsfiddle too.
This is my first post and any help is greatly appreciated- Thanks in advance!!
<INPUT type="button" value="Add Invoice Item" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Item(s)" onclick="deleteRow('dataTable')" />
<form action="" method="post" enctype="multipart/form-data">
<TABLE id="dataTable" width="350px" border="1" style="border-collapse:collapse;">
<TR>
<TH>
<INPUT type="checkbox" name="select-all" id="select-all" onclick="toggle(this);">
</TH>
<TH>Quanity</TH>
<TH>Item</TH>
<TH>Unit Cost</TH>
<TH formula="cost*qty" summary="sum">Price</TH>
</TR>
<TR>
<TD>
<INPUT type="checkbox" name="chk[]">
</TD>
<TD>
<INPUT type="text" id="qty1" name="qty[]" onchange="totalIt()"> </TD>
<TD>
<INPUT type="text" id="item1" name="item[]"> </TD>
<TD>
<INPUT type="text" id="cost1" name="cost[]" onchange="totalIt()"> </TD>
<TD>
<INPUT type="text" id="price1" name="price[]" readonly="readonly" value="0.00"> </TD>
</TR>
</TABLE>
</form>
Sub Total: <input type="text" readonly="readonly" id="total"><br><input type="submit" value="Create Invoice">
<!-------JAVASCRIPT--------->
<script>
function calc(idx) {
var price = parseFloat(document.getElementById("cost" + idx).value) *
parseFloat(document.getElementById("qty" + idx).value);
//alert(idx+":"+price);
document.getElementById("price" + idx).value = isNaN(price) ? "0.00" : price.toFixed(2);
//document.getElementById("total") = totalIt;
}
function totalIt() {
var qtys = document.getElementsByName("qty[]");
var total = 0;
for (var i = 1; i <= qtys.length; i++) {
calc(i);
var price = parseFloat(document.getElementById("price" + i).value);
total += isNaN(price) ? 0 : price;
}
document.getElementById("total").value = isNaN(total) ? "0.00" : total.toFixed(2);
}
window.onload = function() {
document.getElementsByName("qty[]")[0].onkeyup = function() {
calc(1)
};
document.getElementsByName("cost[]")[0].onkeyup = function() {
calc(1)
};
}
var rowCount = 0;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell3 = row.insertCell(1);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
element3.id = "qty" + rowCount;
element3.onkeyup = totalIt;
cell3.appendChild(element3);
var cell4 = row.insertCell(2);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "item[]";
element4.id = "item" + rowCount;
cell4.appendChild(element4);
var cell5 = row.insertCell(3);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "cost[]";
element5.id = "cost" + rowCount;
element5.onkeyup = totalIt;
cell5.appendChild(element5);
var cell6 = row.insertCell(4);
var element6 = document.createElement("input");
element6.type = "text";
element6.name = "price[]";
element6.id = "price" + rowCount;
element6.value = "0.00";
$(element6).attr("readonly", "true");
cell6.appendChild(element6);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
document.getElementById("select-all").checked = false;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
</script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>
$("input").blur(function() {
if ($(this).attr("data-selected-all")) {
//Remove atribute to allow select all again on focus
$(this).removeAttr("data-selected-all");
}
});
$("input").click(function() {
if (!$(this).attr("data-selected-all")) {
try {
$(this).selectionStart = 0;
$(this).selectionEnd = $(this).value.length + 1;
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
} catch (err) {
$(this).select();
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
}
}
});
function toggle(source) {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
}
}
</script>
The error occurs after a row in the middle is deleted due to the current code being bound to the indices that are used in html (e.g. ids like "cost1", "price1" etc).
When totalIt function is invoked, it tries to access rows that have been already deleted. To have this issue fixed, you can abstract from particular indices by using more broad selectors. Here is a drop in replacement totalIt function that does not depend on indices:
function totalIt() {
var costs = document.getElementsByName("cost[]");
var quantities = document.getElementsByName("qty[]");
var prices = document.getElementsByName("price[]");
var total = Array.prototype.reduce.call(costs, function(total, cost, index) {
var price = parseFloat(cost.value) * parseFloat(quantities[index].value);
prices[index].value = isNaN(price) ? "0.00" : price.toFixed(2);
return isNaN(price) ? total : total + price;
}, 0)
document.getElementById("total").value = isNaN(total) ? "0.00" : total.toFixed(2);
}
Also, should you want to recompute the total on row delete - call totalIt in the delete handler (deleteRow). Note that you will likely need to wrap it in setTimeout so that re-computation will occur in the next event loop iteration, after the record is actually removed from DOM

Delete html Row and Delete Column dynamically using Javascript

I'm trying to add and remove the row and column from a table dynamically. While I'm trying this with static contents my code working fine. Same thing I'm trying with fetching data from database and adding deleting row/column it's not working.. added rows are getting deleted but the value contains from mysql row and column not getting deleted.
JavaScript:
//*********************************Start Add Row **********************************************************
function addRowToTable() {
var tbl = document.getElementById('tbl_sales');
var columnCount = tbl.rows[0].cells.length;
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0);
var element_1 = document.createElement("input");
element_1.type = "checkbox";
element_1.setAttribute('id', 'newCheckbox');
cell_1.appendChild(element_1);
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('input');
element_2.type = "text";
element_2.setAttribute('id', 'rows');
element_2.setAttribute('name', 'rows[]');
cell_2.appendChild(element_2);
// For Every Row Added add a textbox on the rest of the cells starting with the 3rd,4th,5th... coloumns going on...
if (columnCount >= 2) {
for (var i = 3; i <= columnCount; i++) {
var newCel = row.insertCell(i - 1);
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.setAttribute('id', 'name');
element_3.setAttribute('name', 'name[]');
newCel.appendChild(element_3);
}
}
}
//***************************** End Add Row ***************************************************************
// *****************************Start Add Column**********************************************************
function addColumn() {
var tblBodyObj = document.getElementById('tbl_sales').tBodies[0];
var rowCount = tblBodyObj.rows.length;
//for every Coloumn Added Add checkbox on first row ----------------------------------------------
var newchkbxcell = tblBodyObj.rows[0].insertCell(-1);
var element_4 = document.createElement("input");
element_4.type = "checkbox";
element_4.setAttribute('id', 'newCheckbox');
newchkbxcell.appendChild(element_4);
//For Every Coloumn Added add Drop down list on second row-------------------------------------
var newselectboxcell = tblBodyObj.rows[1].insertCell(-1);
var element_5 = document.createElement('input');
element_5.type = "text";
element_5.setAttribute('id', 'cols');
element_5.setAttribute('name', 'cols[]');
newchkbxcell.appendChild(element_4);
newselectboxcell.appendChild(element_5);
for (var i = 2; i < tblBodyObj.rows.length; i++) {
var newCell = tblBodyObj.rows[i].insertCell(-1);
var element_6 = document.createElement("input");
element_6.type = "text"
element_6.setAttribute('id', 'name');
element_6.setAttribute('name', 'name[]');
newCell.appendChild(element_6)
}
}
//*****************************Start Delete Selected Rows **************************************************
function deleteSelectedRows() {
var tb = document.getElementById('tbl_sales');
var NoOfrows = tb.rows.length;
for (var i = 0; i < NoOfrows; i++) {
var row = tb.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
tb.deleteRow(i);
NoOfrows--;
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns() {
var tb = document.getElementById('tbl_sales');
var NoOfcolumns = tb.rows[0].cells.length;
for (var clm = 3; clm < NoOfcolumns; clm++) {
var rw = tb.rows[0];
var chkbox = rw.cells[clm].childNodes[0];
console.log(clm, NoOfcolumns, chkbox);
if (null != chkbox && true == chkbox.checked) {
//-----------------------------------------------------
var lastrow = tb.rows;
for (var x = 0; x < lastrow.length; x++) {
tb.rows[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
} else {
//alert("not selected");
}
}
}
function deleteAllRows() {
var tbl = document.getElementById('tbl_sales'); // table reference
lastRow = tbl.rows.length - 1; // set the last row index
// delete rows with index greater then 0
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i); //delete the row
}
}
//*****************************End Delete Selected Columns **************************************************
//window.onload = function () {addColumn();addColumn();addColumn();};
Page:
<table width="30" border="1" id="tbl_sales">
<tr>
<td></td>
<td><strong>Columns</strong> </td>
{php}
$j = 0;
for($i=0;$i<count($rows[0]);$i++)
{
{/php}
<td>
{php} if($j == 0) { {/php}
<input type="button" name="adclmbutton" id="addclmnbutton" value="Add Columns" onclick="addColumn()" />
{php}}else{{/php}
<input type="checkbox" id="newCheckbox">
{php}}{/php}
</td>
{php}$j++;}{/php}
</tr>
<tr>
<td><strong>Rows</strong> </td>
<td><strong>Rows Grid</strong> </td>
{php}
$j = 0;
for($i=0;$i<count($rows[0]);$i++)
{
{/php}
<td><input type="text" name="cols[]" value="{php} echo $rows[0][$i]; {/php}" id=""/></td>
{php}}$i++;{/php}
</tr>
{php}
$seats = $CI->model_theatre->convetTable($m_arr);
unset($seats[0]);
$i = 0;
foreach ($seats as $rowName => $columns)
{
{/php}
<tr >
<td>
{php} if($i == 0) { {/php}
<input type="button" name="addrowbutton" id="adrwbutton" value="Add Row" onclick="addRowToTable();"/>
{php}}else{{/php}
<input type="checkbox" id="newCheckbox">
{php}}{/php}</td>
<td><input type="text" name="rows[]" value="{php}echo $rowName;{/php}" /></td>
{php}
foreach ($columns as $cell)
{
{/php}
<td><label for="textfield"></label><input type="text" name="name[]" value="{php} echo $cell;{/php}" width="50px" /></td>
{php}
}
{/php}
</tr>
{php}
$i++;
}
{/php}
</table>
{php}
}
{/php}
<p>
<input type="button" name="button3" id="button3" value="Remove Selected Row" onClick="deleteSelectedRows()" />
<input type="button" value="Delete all rows" onClick="deleteAllRows()" />
<input type="button" name="button4" id="button4" value="Remove Selected Column" onClick="deleteSelectedColoumns()" />
</p>
When you are adding, deleting row you also need to add, delete that row in database by using AJAX call.

Dynamic creation of table with DOM

Can someone tell me what's wrong with this code? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row. This code creates a table with 2 columns and 3 rows, but it's only text in the cells in the third row (the others are empty).
var tablearea = document.getElementById('tablearea');
var table = document.createElement('table');
var tr = [];
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
for (var i = 1; i < 4; i++){
tr[i] = document.createElement('tr');
for (var j = 1; j < 4; j++){
td1.appendChild(text1);
td2.appendChild(text2);
tr[i].appendChild(td1);
tr[i].appendChild(td2);
}
table.appendChild(tr[i]);
}
tablearea.appendChild(table);
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
It is because you're only creating two td elements and 2 text nodes.
Creating all nodes in a loop
Recreate the nodes inside your loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table');
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
table.appendChild(tr);
}
tablearea.appendChild(table);
Creating then cloning in a loop
Create them beforehand, and clone them inside the loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table'),
tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
for (var i = 1; i < 4; i++) {
table.appendChild(tr.cloneNode( true ));
}
tablearea.appendChild(table);
Table factory with text string
Make a table factory:
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
Table factory with text string or callback
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
function populateTable(table, rows, cells, content) {
var is_func = (typeof content === 'function');
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
var text = !is_func ? (content + '') : content(table, i, j);
row.cells[j].appendChild(document.createTextNode(text));
}
table.appendChild(row);
}
return table;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.
Edit:
Revise your code like so:
for (var i = 1; i < 4; i++)
{
tr[i] = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.appendChild(document.createTextNode('Text1'));
td2.appendChild(document.createTextNode('Text2'));
tr[i].appendChild(td1);
tr[i].appendChild(td2);
table.appendChild(tr[i]);
}
<title>Registration Form</title>
<script>
var table;
function check() {
debugger;
var name = document.myForm.name.value;
if (name == "" || name == null) {
document.getElementById("span1").innerHTML = "Please enter the Name";
document.myform.name.focus();
document.getElementById("name").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span1").innerHTML = "";
document.getElementById("name").style.border = "2px solid green";
}
var age = document.myForm.age.value;
var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;
if (age == "" || age == null) {
document.getElementById("span2").innerHTML = "Please provide Age";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else if (!ageFormat.test(age)) {
document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span2").innerHTML = "";
document.getElementById("age").style.border = "2px solid green";
}
var password = document.myForm.password.value;
if (document.myForm.password.length < 6) {
alert("Error: Password must contain at least six characters!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[0-9]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one number (0-9)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[a-z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[A-Z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[$&+,:;=?##|'<>.^*()%!-]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one special character!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span3").innerHTML = "";
document.getElementById("password").style.border = "2px solid green";
}
if (document.getElementById("data") == null)
createTable();
else {
appendRow();
}
return true;
}
function createTable() {
var myTableDiv = document.getElementById("myTable"); //indiv
table = document.createElement("TABLE"); //TABLE??
table.setAttribute("id", "data");
table.border = '1';
myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv)
debugger;
var header = table.createTHead();
var th0 = table.tHead.appendChild(document.createElement("th"));
th0.innerHTML = "Name";
var th1 = table.tHead.appendChild(document.createElement("th"));
th1.innerHTML = "Age";
appendRow();
}
function appendRow() {
var name = document.myForm.name.value;
var age = document.myForm.age.value;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = name;
row.insertCell(1).innerHTML = age;
clearForm();
}
function clearForm() {
debugger;
document.myForm.name.value = "";
document.myForm.password.value = "";
document.myForm.age.value = "";
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
return true;
}
else {
return false;
}
}
</script>
<div>
<form name="myForm">
<table id="tableid">
<tr>
<th>Name</th>
<td>
<input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<th>Age</th>
<td>
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
name="age" id="age" /></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="password" name="password" id="password" placeholder="Password" /></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" onclick="check();" /></td>
<td>
<input type="reset" name="Reset" /></td>
</tr>
</table>
</form>
<div id="myTable">
</div>
</div>
var html = "";
for (var i = 0; i < data.length; i++){
html +="<tr>"+
"<td>"+ (i+1) + "</td>"+
"<td>"+ data[i].name + "</td>"+
"<td>"+ data[i].number + "</td>"+
"<td>"+ data[i].city + "</td>"+
"<td>"+ data[i].hobby + "</td>"+
"<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);
You can create a dynamic table rows as below:
var tbl = document.createElement('table');
tbl.style.width = '100%';
for (var i = 0; i < files.length; i++) {
tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
::::: // As many <td> you want
td1.appendChild(document.createTextNode());
td2.appendChild(document.createTextNode());
td3.appendChild(document.createTextNode();
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbl.appendChild(tr);
}
when you say 'appendchild' you actually move your child from one parent to another.
you have to create a node for each cell.
In my example, serial number is managed according to the actions taken on each row using css. I used a form inside each row, and when new row created then the form will get reset.
/*auto increment/decrement the sr.no.*/
body {
counter-reset: section;
}
i.srno {
counter-reset: subsection;
}
i.srno:before {
counter-increment: section;
content: counter(section);
}
/****/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$('#POITable').on('change', 'select.search_type', function (e) {
var selectedval = $(this).val();
$(this).closest('td').next().html(selectedval);
});
});
</script>
<table id="POITable" border="1">
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Your Name</th>
<th>Number</th>
<th>Input</th>
<th>Chars</th>
<th>Action</th>
</tr>
<tr>
<td><i class="srno"></i></td>
<td>
<select class="search_type" name="select_one">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="xyz">xyz</option>
</select>
</td>
<td></td>
<td>
<select name="select_two" >
<option value="">Select</option>
<option value="123">123</option>
<option value="456">456</option>
<option value="789">789</option>
</select>
</td>
<td><input type="text" size="8"/></td>
<td>
<select name="search_three[]" >
<option value="">Select</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
</td>
<td><button type="button" onclick="deleteRow(this)">-</button><button type="button" onclick="insRow()">+</button></td>
</tr>
</table>
<script type='text/javascript'>
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
//new_row.cells[0].innerHTML = len; //auto increment the srno
var inp1 = new_row.cells[1].getElementsByTagName('select')[0];
inp1.id += len;
inp1.value = '';
new_row.cells[2].innerHTML = '';
new_row.cells[4].getElementsByTagName('input')[0].value = "";
x.appendChild(new_row);
}
</script>
Hope this helps.
In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.
<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="dataGridForItem">
</div>
</div>
</div>
//Call Function From Button click Event
var counts = 1;
function add(){
var Weightage = $('#Weightage').val();
var ItemName = $('#ItemName option:selected').text();
var ItemNamenum = $('#ItemName').val();
generateTable(Weightage,ItemName,ItemNamenum);
$('#Weightage').val('');
$('#ItemName').val(-1);
return true;
}
function generateTable(Weightage,ItemName,ItemNamenum){
var tableHtml = '';
if($("#rDataTable").html() == undefined){
tableHtml = generateHeader();
}else{
tableHtml = $("#rDataTable");
}
var temp = $("<div/>");
var row = addToRow(Weightage,ItemName,ItemNamenum);
$(temp).append($(row));
$("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}
//Generate Header
function generateHeader(){
var html = "<table id='rDataTable' class='table table-striped'>";
html+="<tr class=''>";
html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
html+="</tr></table>";
return html;
}
//Add New Row
function addToRow(Weightage,ItemName,ItemNamenum){
var html="<tr class='trObj'>";
html+="<td>"+counts+"</td>";
html+="<td>"+ItemName+"</td>";
html+="<td>"+Weightage+"</td>";
html+="</tr>";
counts++;
return html;
}
You can do that using LemonadeJS.
<html>
<script src="https://lemonadejs.net/v2/lemonade.js"></script>
<div id='root'></div>
<script>
var Component = (function() {
var self = {};
self.rows = [
{ title:'Google', description: 'The alpha search engine...' },
{ title:'Bind', description: 'The microsoft search engine...' },
{ title:'Duckduckgo', description: 'Privacy in the first place...' },
];
// Custom components such as List should always be unique inside a real tag.
var template = `<table cellpadding="6">
<thead><tr><th>Title</th><th>Description</th></th></thead>
<tbody #loop="self.rows">
<tr><td>{{self.title}}</td><td>{{self.description}}</td></tr>
</tbody>
</table>`;
return lemonade.element(template, self);
});
lemonade.render(Component, document.getElementById('root'));
</script>
</html>

Dynamically add new table row in Javascript

I used normal addRow function and removeRow function to dynamically add and remove the row in a table.
function addRow()
{
var ptable = document.getElementById('ptableQuestion');
var lastElement = ptable.rows.length;
var index = lastElement;
var row = ptable.insertRow(lastElement);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(index);
cellLeft.appendChild(textNode);
var cellText = row.insertCell(1);
var element = document.createElement('textarea');
element.name = 'question' + index;
element.id = 'question' + index;
element.rows="2";
element.cols="60"
var cellText1 = row.insertCell(2);
var element1 = document.createElement('input');
element1.type = 'checkbox';
element1.name = 'cb';
element1.id = 'cb';
cellText.appendChild(element);
cellText1.appendChild(element1);
document.getElementById("psize").value=index;
}
function checkCheckboxes() {
var e = document.getElementsByName("cb");
var message = 'Are you sure you want to delete?';
var row_list = {length: 0};
for (var i = 0; i < e.length; i++) {
var c_box = e[i];
if (c_box.checked == true) {
row_list.length++;
row_list[i] = {};
row_list[i].row = c_box.parentNode.parentNode;
row_list[i].tb = row_list[i].row.parentNode;
}
}
if (row_list.length > 0 && window.confirm(message)) {
for (i in row_list) {
if (i == 'length') {
continue;
}
var r = row_list[i];
r.tb.removeChild(r.row);
}
} else if (row_list.length == 0) {
alert('You must select an email address to delete');
}
}
<form action="show.jsp" method="post" onsubmit="return validate();">
<input type="hidden" name="psize" id="psize">
<table style="border:1px solid #000000;" bgcolor="#efefef"
id="ptablePerson" align="center">
<tr>
<th colspan="3">Add New Person</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="person1" id="person1" size="30" />
<input type="button" value="Add" onclick="addRow();" /></td>
<td><input type="checkbox" id="cb" name="cb"/></td>
</tr>
</table>
<table align="center">
<tr>
<td><input type="button" value="Remove" onclick="checkCheckboxes();" />
<input type="Submit" value="Submit" /></td>
</tr>
</table>
</form>
</BODY>
</HTML>
My problem is when the table got 5 row, if i click checkbox to delete row 3 the index become 1 2 4 5. Is there any method can rearrange it to 1 2 3 4
This looks like simple delete element from the list. You have to get all the rows of the table, and shift all rows one step backword after delete operation is completed.
There is a small code i which i has created a spn in every td.So that I will replace the value in the iterartion. It will work if u deleted 3(1,2,3,4,5) then the content of span will be 1,2,3,4 .Jquery i am using here
var rowCount = $('#ptableQuestion tr').length;
if (rowCount != 0) {
i = 0;
$('#ptableQuestion tr').each(function(i) {
$(this).find("td .spn").html(i);
});
}
});
Hope it will work for you.

Categories