Delete html Row and Delete Column button using Javascript - javascript

I am trying to achieve like the pic below:
I don't seem to get the "delete selected column" right and also Delete selected row; instead the are deleting all rows and all columns.
So far I have the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
//*********************************Start Add Row **********************************************************
function addRowToTable(){
var tbl = document.getElementById('tbl_sales'); //html table
var columnCount = tbl.rows[0].cells.length; //no. of columns in table
var rowCount = tbl.rows.length; //no. of rows in table
var row = tbl.insertRow(rowCount); //insert a row method
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0); //Create a new cell
var element_1 = document.createElement("input"); //create a new element
element_1.type = "checkbox"; //set element type
element_1.setAttribute('id','newCheckbox'); //set id attribute
cell_1.appendChild(element_1); //Append element to created cell
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('select');
element_2.name = 'SelDist' + rowCount;
element_2.options[0] = new Option('John Doe', 'value0');
element_2.options[1] = new Option('Dane Doe', 'value1');
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){ //Add cells for more than 2 columns
for (var i=3; i<=columnCount; i++) {
var newCel = row.insertCell(i-1); //create a new cell
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.setAttribute('id', 'newInput'); //set the id attribute
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('select');
element_5.name = 'SelProd' + rowCount;
element_5.options[0] = new Option('Product11', 'value0');
element_5.options[1] = new Option('Product12', 'value1');
element_5.options[2] = new Option('Product13', 'value2');
element_5.options[3] = new Option('Product14', 'value3');
element_5.options[4] = new Option('Product15', 'value4');
element_5.options[5] = new Option('Product16', 'value5');
newselectboxcell.appendChild(element_5);
// For Every Coloumn Added add a textbox on the rest of the row cells starting with the 3rd,4th,5th......
for (var i=2; i< tblBodyObj.rows.length; i++) { //Add cells in all rows starting with 3rd row
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
var element_6 = document.createElement("input");
element_6.type = "text"
element_6.setAttribute('id', 'Newinput');
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]; //get check box object
if(null != chkbox && true == chkbox.checked) { //wheather check box is selected
tb.deleteRow(i); //delete the selected row
NoOfrows--; //decrease rowcount by 1
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns()
{
var tb = document.getElementById('tbl_sales');//html table
var NoOfcolumns = tb.rows[0].cells.length; //no. of columns in table
for (var clm=3; clm< NoOfcolumns; clm++)
{
var rw = tb.rows[0];
var chkbox = rw.cells[clm].childNodes[0];
if(null != chkbox && true == chkbox.checked)
{
//-----------------------------------------------------
var lastrow = document.getElementById('tbl_sales').rows;
for (var x=0; x< lastrow.length; x++)
{
lastrow[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
}else
{
alert ("not selected");
return;
}
}
}
//*****************************End Delete Selected Columns **************************************************
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Distributor Sales</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="30" border="1" id="tbl_sales">
<tr>
<td></td>
<td><strong>Products</strong></td>
<td><input type="button" name="adclmbutton" id="addclmnbutton" value="Add Product" onclick="addColumn()" /></td>
</tr>
<tr>
<td><strong>Distributors</strong></td>
<td><strong>Sales Grid</strong></td>
<td><select name="select3" id="select">
<option>Product 1</option>
<option>Product 2</option>
<option selected="selected">Product 3</option>
</select></td>
</tr>
<tr>
<td><input type="button" name="addrowbutton" id="adrwbutton" value="Add Distributor" onclick="addRowToTable();"/></td>
<td><select name="select6" id="select6">
<option selected="selected">Jhon Doe</option>
<option>Jane Doe</option>
<option>David</option>
<option>Kelvin</option>
</select></td>
<td><label for="textfield"></label>
<input type="text" name="textfield" id="textfield" width="50px" /></td>
</tr>
</table>
<p>
<input type="submit" name="button3" id="button3" value="Remove Selected Distributor" onClick="deleteSelectedRows()"/>
<input type="submit" name="button4" id="button4" value="Remove Selected Product" onClick="deleteSelectedColoumns()"/>
</p>
</form>
</body>
</html>

Change this line:
lastrow[x].deleteCell(clm);
to
tb.rows[x].deleteCell(clm);
and also remove the branch
//} else { alert ("not selected"); return; }
,then it works well. Tested it here.

Your deleteSelectedColumns function will always return after passing a column which is not selected:
/*...*/
if(null != chkbox && true == chkbox.checked)
{
/*...*/
}else
alert ("not selected");
return;
}
If the first column is not selected, for instance, none of the others will be looked at.
You are also using submit buttons to trigger your functions. These will refresh the page when pressed (reseting it to its original state), giving the impression that all rows and columns have been deleted. Try using
<input type="button" />
instead.

if table is static, then you can use the below to delete first, last column:
var allRows = document.getElementById('destination').rows;
for(var i=0; i< allRows.length; i++) {
if (allRows[i].cells.length > 0) {
allRows[i].deleteCell(-1);// logic to remove the last column
allRows[i].deleteCell(0);// logic to remove the first column of the modified table.
}
}

Related

How can I inspect if an element inside a cell is checked?

The function "insert()" makes table cells that contain task names given by input. Every task name has a checkbox appended and how can I inspect if an element in a cell is checked so I can change its properties? I want the function "completeTasks()" to check for a checked element so when I press the button that calls the function, elements that are checked should be green and strikethrough(line-through).
<html>
<head>
</head>
<body>
Task Name: <input type="text" id="name">
<button id="ins" onclick="insert()">Insert</button>
<table id="tabl3">
</table>
<button id="comp" onclick="completeTasks()">Complete Tasks</button>
<button id="del" onclick="deleteTasks()">Delete Tasks</button>
<script type="text/javascript">
var i=0;
var r=0;
var arrName = [];
function insert()
{
var chk = document.createElement("input");
chk.setAttribute("type", "checkbox");
arrName[i] = document.getElementById("name").value;
var table = document.getElementById("tabl3");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
r++;// counting the rows so i can delete them all later if i want to
cell1.innerHTML = arrName[i];
cell1.appendChild(chk); // appending a checkbox to the element so i can check it later
i++;
}
function completeTasks(){
// if one or more elements are checked when clicking this button
// then the checked task name(s) would have green color and have a line-through text decoration.
//.style.color = "green";
//.style.textDecoration = "line-through";
}
function deleteTasks(){
// will probably have to delete all the cells so i did it like this
for(let c = 0; c<r; c++){
document.getElementById("tabl3").deleteRow(0);
}
}
</script>
</body>
</html>
You can first target all the checked check box using Document.querySelectorAll(), then loop through them and set the style to the closest td element.
Demo:
Task Name: <input type="text" id="name">
<button id="ins" onclick="insert()">Insert</button>
<table id="tabl3">
</table>
<button id="comp" onclick="completeTasks()">Complete Tasks</button>
<button id="del" onclick="deleteTasks()">Delete Tasks</button>
<script type="text/javascript">
var i=0;
var r=0;
var arrName = [];
function insert()
{
var chk = document.createElement("input");
chk.setAttribute("type", "checkbox");
arrName[i] = document.getElementById("name").value;
var table = document.getElementById("tabl3");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
r++;// counting the rows so i can delete them all later if i want to
cell1.innerHTML = arrName[i];
cell1.appendChild(chk); // appending a checkbox to the element so i can check it later
i++;
}
function completeTasks(){
var checkedEl = document.querySelectorAll('#tabl3 input:checked'); // get all the checked checkbox inside the table
checkedEl.forEach(function(el){ //loop through them
el.closest('td').style.color = "green";
el.closest('td').style.textDecoration = "line-through";
});
}
function deleteTasks(){
// will probably have to delete all the cells so i did it like this
for(let c = 0; c<r; c++){
document.getElementById("tabl3").deleteRow(0);
}
}
</script>

Disable selected option of the first select box in the second select box

I want to find student's data by inserting their subject name and their score range. The teacher can add a new subject with an add button and can remove the subject too. Also the subject/option that has been already selected in the previous row will disable in the next new row.
Here is the html code
<button type="button" class="btn btn-bricky btn-sm" onclick="deleteRow('dataTable')"><span class="glyphicon glyphicon-remove"></span> Delete Row</button>
<table id="dataTable" class="table table-striped" style="font-size: 12px" >
<tr>
<td><input type="checkbox" name="chk"/></td>
<td>
<select name="subject" id="subject">
<option value="Math">Math</option>
<option value="Physic">Physic</option>
<option value="Chemistry">Chemistry</option>
<option value="Biology">Biology</option>
</select>
Score Min : <input type="number" name="comsMin" style="width:70px" min="0" max="100"/>
Max : <input type="number" name="comsMax" style="width:70px" min="0" max="100"/></td>
</tr>
</table>
And here is the JavaScript code
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "#text":
newcell.childNodes[0].value = "";
break;
case "#checkbox":
newcell.childNodes[0].checked = false;
break;
case "#select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
//--------------
function deleteRow(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) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
My problem is that I don't know how and where to write a code to disable the selected option that had been chosen in the first select box in the new added select box.
Is this possible?
Here's JS fiddle
We can have a separate table for storing the dataset in hidden mode and maintain the selection state in it.
Instead of hidden element you can also maintain the state in javascript variables.
function syncModdelAdd(tableID){
// Get the available selections
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var dataTable = document.getElementById('dataTable');
for(var i=0; i<rowCount; i++){
var selectedIndex = table.rows[i].cells[1].childNodes[1].selectedIndex;
dataTable.rows[0].cells[1].childNodes[1].options[selectedIndex].disabled=true;
}
}
function syncModelDelete(selectedIndex){
var dataTable = document.getElementById('dataTable');
dataTable.rows[0].cells[1].childNodes[1].options[selectedIndex].disabled=false;
var table = document.getElementById('resultTable');
var totalRows = table.rows.length;
table.rows[totalRows-1].cells[1].childNodes[1].options[selectedIndex].disabled=false;
}
Fiddle Link : https://jsfiddle.net/2tfacL9k/

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 Row, Save Changes once I edit table using Javascript

Someone posted this:
Making row editable when hit row edit button
I wanted to create one delete/edit/save button so that person can enter the order number and delete or edit the data.
Sequencing steps:
On Delete:
I click delete button, the prompt box comes up, I enter 1, it deletes 1.
I click delete button, the prompt box comes up, I enter 2, it does not delete 2.
However:
I click delete button, the prompt box comes up, I enter 2, it deletes 2.
I click delete button, the prompt box comes up, I enter 1, it does not delete 1.
Edit Button works, but when I click on the save button, it won't save the changes
https://jsfiddle.net/nhgjdr00/8/
HTML:
<table id="myTable" border="1">
<thead>
<th>Order #</th>
<th>Name</th>
<th>Tea Order</th>
<th>Tea Size</th>
</thead>
<tbody>
<tr>
<td class="rowNumber">1</td>
<td>Shakespeare</td>
<td>Iced</td>
<td>Small</td>
</tr>
<tr>
<td class="rowNumber">2</td>
<td>Frost</td>
<td>Hot</td>
<td>Medium</td>
</tr>
</tbody>
</table>
<br>
<input id="deleteRowBtn" type="button" value="Delete Row" />
<input id="editBtn" type="button" value="edt" />
<input id="saveBtn" type="button" value="saveChange" />
<br>
<br>
<form name="create"2 style="width:80px;">
Name:<input type="text" id="txtname" />
<br>
Tea Order:<input type="text" id="txtTeaOrder" name="txtTeaOrder" />
<br>
Tea Size<input type="text" id="txtTeaSize" name="txtTeaSize" />
<br>
</form>
</body>
JS:
"use strict";
var orderNumberHolder=[]; // holds each order number
// returns a html element (id)
var $ = function(id) {
return document.getElementById(id);
};
function deleteRow() {
var orderNumber = parseInt(prompt ("enter order number to delete"));
if (orderNumber == NaN || orderNumber < 1) {
prompt ("enter order number");
} else {
var table = $("myTable");
var rowCount = table.rows.length; // eliminate header so minus 1
for(var i=0, j=0; i<rowCount; i++, j++) {
var row = table.rows[i];
if (orderNumber == i) {
table.deleteRow(i);
rowCount--;
table.rows[j].cells[0].innerHTML = j; // renumbers the list after delete row
}
}
}
}
function edt() {
// converts number into integer
var orderNumber = parseInt(prompt ("enter order number to edit"));
// need to store order number so I can reference when I save edit info
orderNumberHolder.push(orderNumber);
if (orderNumber == NaN || orderNumber < 1) {
prompt ("enter order number");
} else {
var table = $("myTable");
var rowCount = table.rows.length;
// i is index, so start with 1 so it doesn't include header
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
if (orderNumber == i){
$("txtname").value = table.rows[i].cells["1"].innerHTML;
$("txtTeaOrder").value = table.rows[i].cells["2"].innerHTML;
$("txtTeaSize").value = table.rows[i].cells["3"].innerHTML;
}
}
}
}
function saveChange() {
var table = $("myTable");
var rowCount = table.rows.length; // do not want to include header
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
if (orderNumberHolder[i] == i){
table.rows[i].cells["1"].innerHTML = $("txtname").value ;
table.rows[i].cells["2"].innerHTML = $("txtauthor").value;
table.rows[i].cells["3"].innerHTML = $("txtcdate").value;
$("txtname").value = '';
$("txtauthor").value = '';
$("txtcdate").value = '' ;
rowCount--;
}
}
}
window.onload = function() {
$("deleteRowBtn").onclick = deleteRow; // calls function
$("editBtn").onclick = edt; // calls function
$("saveBtn").onclick = saveChange; // calls function
}
I would appreciate any suggestions.
You are taking the row number and deleting that row. When u delete the first row then row number of existing element ie (order# 2) changes to 1 from 2. Hence when you enter 2 in prompt there is no such row to delete.

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.

Categories