In the below dynamic form rows can be added or removed dynamically. Calculation involves finding the difference between cost price and the selling price of a product.
What I like to implement (and trying in vain for the last one week or so) is to set the background color of the result cell to red if the value is negative and to green if the value is positive. Though I came across several solutions on this site unfortunately I was unable to implement them to solve this.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>CSS</title>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 5) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
//var row = table.insertRow(rowCount-1);
var colCount = table.rows[0].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum 5 Rows Only.");
}
}
function deleteRow(tableID) {
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) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Records.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
<script>
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var num1 = mainRow.querySelectorAll('[name=num1]')[0].value;
var num2 = mainRow.querySelectorAll('[name=num2]')[0].value;
var result = mainRow.querySelectorAll('[name=result]')[0];
var result1 = num2 - num1;
result.value = result1;
}
</script>
<body>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id='row_0'>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td>
<label>Cost Price</label>
<input type="text" size="1" required="required" name="num1" class="num1" id="num1" oninput="calculate('row_0')"/>
</td>
<td>
<label>Selling Price</label>
<input type="text" size="1" required="required" name="num2" class="num2" id="num2" oninput="calculate('row_0')"/>
</td>
<td>
<label>Difference</label>
<input type="text" size="1" required="required" name="result" class="result" id="result" />
</td>
</tr>
</tbody>
</table>
</body>
</html>
Aside from the HTML issues (as noted in the comments on your question) you can achieve your goal by checking the result1 variable is greater than zero, and applying the relevant style to the parent td of the input. Try this:
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var num1 = mainRow.querySelectorAll('[name=num1]')[0].value;
var num2 = mainRow.querySelectorAll('[name=num2]')[0].value;
var result = mainRow.querySelectorAll('[name=result]')[0];
var cell = result.parentElement;
var result1 = num2 - num1;
result.value = result1;
var cellBackground = result1 < 0 ? 'red' : 'transparent';
cell.style.backgroundColor = cellBackground;
}
Example fiddle
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var num1 = mainRow.querySelectorAll('[name=num1]')[0].value;
var num2 = mainRow.querySelectorAll('[name=num2]')[0].value;
var result = mainRow.querySelectorAll('[name=result]')[0];
var result1 = num2 - num1;
result.value = result1;
if(result1 < 0){
$(result).parent().css("background", "red");
}else{
$(result).parent().css("background", "");
}
}
Related
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
I would like a form where a user can add and remove rows.
Once the input has been added the respective fields will update by multiplying the qty * cost, as well as the bottom total field.
As I am new to js, I used the code from a pervious answer
However, the remove function is not working.
I have tried other solutions, however when a row gets removed the values don't update.
The ultimate goal is for a user to create a Quote with the tables and post it to a mysql database using ajax.
Therefore I changed the querySelectorAll to a class, for example class=qty, as more than one of the same id is not allowed.
Below is what I have so far.
The form:
<form name="add_name" id="add_service">
<table id="dataTable" class="form" border="1">
<tbody>
<tr id='row_0'>
<td>
<label>Service</label>
<input type="text" required="required"
name="service[]">
</td>
<td>
<label>Quantity</label>
<input type="text" class="qty" required="required"
name="qty[]" oninput="calculate('row_0')">
</td>
<td>
<label for="price">Price</label>
<input type="text" class="cost" required="required"
name="cost[]" oninput="calculate('row_0')">
</td>
<td>
<label for="total">Total</label>
<input type="text" class="subtotal"
required="required" name="subtotal[]">
</td>
<!--<td>
<a class="remove" href="#">Remove</a>
</td>-->
</tr>
</tbody>
</table>
<div>
<input type="text" class="" id="grand_total">
</div>
<input type="button" name="submit" id="submit" class="btn btn-
info" value="Submit"/>
</form>
<script>
$(document).ready(function () {
/**$('table').on('click', 'tr a.remove', function (e) {
e.preventDefault();
$(this).closest('tr').remove();
});*/
//submit data
$('#submit').click(function () {
$.ajax({
url: "push.php",
method: "POST",
data: $('#add_service').serialize(),
success: function (data) {
alert(data);
$('#add_service')[0].reset();
}
});
});
});
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_' + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.getElementsByTagName("input")
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" +
row.id + "')");
}
} else {
alert("Maximum 10.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll('[class=qty]')[0].value;
var myBox2 = mainRow.querySelectorAll('[class=cost]')[0].value;
var total = mainRow.querySelectorAll('[class=subtotal]')[0];
var myResult1 = myBox1 * myBox2;
total.value = myResult1;
grandtotal();
}
function grandtotal(){
//calculation script
var $form = $('#add_service'),
$sumDisplay = $('#grand_total');
var $summands = $form.find('.subtotal');
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
}
</script>
From the question it is unclear how addRow is being called. I will assume that it is triggered by an event. You will need to uncomment the remove td and set the value of onclick:
<td>
<input type="button" class="remove" value="Remove" onclick="removeRow('dataTable', '0');">
</td>
and modify addRow as follows:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = 'row_' + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.getElementsByTagName("input")
for (i = 0; i < listitems.length - 1; i++) {
listitems[i].setAttribute("oninput", "calculate('" +
row.id + "')");
}
listitems[listitems.length - 1].setAttribute("onclick", "removeRow('dataTable', " + row.id + ")");
} else {
alert("Maximum 10.");
}
}
This should result in your remove being generated. But we have a problem with ids, since if you remove the second row and there is a third row, then the way you specify the ids will result in duplicate ids. Therefore, if you remove an item, the ids of the subsequent rows will have to be decreased. Let's implement removeRow:
function removeRow(tableID, index) {
//Removing the row
var table = document.getElementById(tableID);
table.deleteRow(index);
//Modifying the ids of subsequent rows
var rowCount = table.rows.length;
for (var i = index; i < rowCount; i++) {
table.rows[i].id = "row_" + i;
}
//Handling the counts
grandtotal();
}
The code is untested, if you have any problem with it, I advise you to create a JSFiddle, so I will be able to easily test the code I have written.
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>
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.
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.