How to select all checkboxes from table using javascript - javascript

Script:-
<script type="text/javascript">
$(document).ready(function () {
$("#cbSelectAll").click(function () {
if (this.checked) {
$(':checkbox').each(function () {
this.checked = true;
var selectall = document.getElementsByClassName(".checkBoxClass");
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var hidCustomer = document.getElementById("hfCustomerID");
hidCustomer = '';
var str = 'Select All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$("#GridRows .checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'Select All + unselected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
else {
$(':checkbox').each(function () {
this.checked = false;
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'UnSelect All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$(".checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'unSelect All + selected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
});
});
</script>
HTML:-
<body>
<h4>Number Of Records - <span>#ViewBag.ItemCount</span> </h4>
<div class="table-responsive" style="padding-left:20%;">
<table class="table-fill" style="float:left;">
<thead>
<tr>
<th class="text-left">
Select All
<div class="checkbox">
<input style="margin-left:15px;" type="checkbox" id="cbSelectAll" />
</div>
</th>
<th class="text-left" style="padding-left:27px;">
First Name
</th>
<th class="text-left" style="padding-left:32px;">
Last Name
</th>
<th class="text-left" style="padding-left:40px;padding-right: 60px;">
Email-ID
</th>
<th class="text-left" style="padding-left:30px;padding-right: 40px;">
Customer Type
</th>
<th class="text-left" style="padding-left:15px;">
Customer Designation
</th>
</tr>
</thead>
</table>
<div id="GridRows" style="width:65%;">
</div>
</div>
<div id="pager"></div>
<input type="hidden" id="currentPage">
<input type="hidden" id="hfCustomerID"/>
<input type="hidden" id="hfSelectAll" />
</body>
this is html. Rows generated dynamically from jquery ajax call to avoid loss of values stored in hidden field on page load.
In this when clicked on select all checked box all values of table
from same page selected.
how to store all values of table from multiple pagination when clicked
on Select All checkbox?
what are option for storing all values of table?

Actually your checkAll(..) is hanging without any attachment.
1) Add onchange event handler
2) Modified the code to handle check/uncheck
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 = "chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
cell3.innerHTML = rowCount;
var cell4 = row.insertCell(3);
cell4.innerHTML = rowCount;
var cell5 = row.insertCell(4);
cell5.innerHTML = rowCount;
var cell6 = row.insertCell(5);
cell6.innerHTML = rowCount;
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
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);
}
}
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" border="1">
<tr>
<th>
<INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" />
</th>
<th>Make</th>
<th>Model</th>
<th>Description</th>
<th>Start Year</th>
<th>End Year</th>
</tr>
</TABLE>

You can if you are using datatable.
$(document).ready(function () {
var oTable = $('#example').dataTable({
stateSave: true
});
var allPages = oTable.fnGetNodes();
$('body').on('click', '#selectAll', function () {
if ($(this).hasClass('allChecked')) {
$('input[type="checkbox"]', allPages).prop('checked', false);
} else {
$('input[type="checkbox"]', allPages).prop('checked', true);
}
$(this).toggleClass('allChecked');
})
});
There is one more option i.e. you have to add same class name on all checkboxes and add this code.(If you not use datatable).
var select_all = document.getElementById("select_all");
var checkboxes = document.getElementsByClassName("checkbox");
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item isunchecked
if(this.checked == false){
select_all.checked = false;
}
if(document.querySelectorAll('.checkbox:checked').length ==checkboxes.length){
select_all.checked = true;
}
});
}

Related

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

Need help updating the index for selected row

I have been stuck on an issue where I am trying to use Javascript to add and remove a row from a table.
I got the add part working, the delete somewhat. The delete fails if you delete the first row or a row in the middle (live code can be seen here
I uploaded its code on PasteBin
<script type="text/javascript">
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow){
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function(){
if (document.getElementById('whatToDo').value != ""){
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
row.addEventListener('click', theIndex.bind(null, currentRow));
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
if (theRow > 0){
document.getElementById("myList").deleteRow(theRow);
document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0){
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
</script>
I am learning Javascript and wanted to do more than the exercise that was being given by adding new features to it.
Your approach to mark the current selected row has some issues:
row.addEventListener('click', theIndex.bind(null, currentRow));
Instead of using a global variable I suggest to use a row attribute (or class). Hence, change that line to:
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
Add the attribute selected for the current row and remove the same attribute for other rows.
In this way, when you need to get the current selected row you can simply:
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow) {
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function () {
if (document.getElementById('whatToDo').value != "") {
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
//row.addEventListener('click', theIndex.bind(null, currentRow));
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
if (theRow > 0) {
document.getElementById("myList").deleteRow(theRow);
//document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " + theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0) {
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
<div class="container">
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover">
<tr>
<td colspan="3">
<h1>To Do List Example</h1>
</td>
</tr>
<tr>
<th><label>Item</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
<tr>
<td>
<input type="text" id="whatToDo" value="">
</td>
<td>
<input type="date" id="whenToDo" value="">
</td>
<td>
<input type="text" id="whereToDo" value="">
</td>
</tr>
<tr>
<td>
<button id="addItem" class="btn btn-default btn-primary active">
<i class="fas fa-plus"></i> Add This Item
</button>
</td>
<td>
<button id="markAsDone" class="btn btn-default ">
<i class="fas fa-check"></i> Mark As Done
</button>
</td>
<td>
<button id="removeItem" class="btn btn-default">
<i class="fas fa-trash-alt"></i> Remove Item
</button>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover" id="myList">
<tr>
<th><label></label></th>
<th><label>Event</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
</table>
</div>
</div>
</div>
This line is throwing a null value error:
document.getElementById('whatToMark').value = "";
Neither in your JS, nor in your HTML, do you ever set an element to the ID of whatToMark.

JavaScript Type Error 'childnodes' undefined

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>

Add Rows and Cols to a HTML Table

I'm trying to figure out how to add a new row to a table using Javascript but I also need to be able to add 3 columns into this table and here is where I am having problems. I can't seem to get it to work. Here is the javascript:
This adds rows with first field being ID entered into the first row but I don't know how to fill in columns.
function myCreateFunction() {
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++) {
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var div1 = document.createElement('div');
div1.innerHTML = "ID";
cell1.appendChild(div1);
div1.contentEditable = true;
}
}
Here is my Table:
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
try this
function myCreateFunction(thisObj) {
var buttonTr = thisObj.parentNode.parentNode;
var buttonTrHTML = buttonTr.outerHTML;
buttonTr.parentNode.removeChild(buttonTr);
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++)
{
table.innerHTML += "<tr><td>ID</td> <td>First Name</td><td>Last Name</td> <td>Add More</td><tr>";
}
//table.innerHTML += buttonTrHTML ;
table.appendChild(buttonTr );
}
and you need to pass the current Obj as
<button onclick="myCreateFunction(this)">Create row</button>
Try this
function myCreateFunction() {
var table = document.getElementById("myTable");
var rows = table.rows.length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "ID";
cell1.contentEditable = true;
cell2.innerHTML = "First Name";
cell2.contentEditable = true;
cell3.innerHTML = "Last Name";
cell3.contentEditable = true;
var but1 = document.createElement('button');
but1.innerHTML = "Create row";
but1.setAttribute("onclick", "myCreateFunction()");
cell4.appendChild(but1);
var but2 = document.createElement('button');
but2.innerHTML = "Delete row";
but2.setAttribute("onclick", "myDeleteFunction()");
cell4.appendChild(but2);
}
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button><button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
I solved this a bit different. And it works fine (also with deleting rows):
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var maxRows = 10;
if (rowCount < maxRows) {
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;
}
} else {
alert("Max. Tabs= " + maxRows);
}
}
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 (chkbox != null && chkbox.checked == true) {
if (rowCount <= 1) {
alert("Min Tabs = 1");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Try following function
function myCreateFunction() {
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
console.log(rowCount)
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = rowCount;
cell2.innerHTML = ""; //put your text/html here
cell2.innerHTML = ""; //put your text/html here
}
put your desired text or html in innerHTML of the respected cell
Also for Pavel's answer your markup is wrong(though I haven't tested the function). The table id 'myTable' should be passed as string.
<button onclick="addRow('myTable')">Create row</button>
could not comment for not having enough reputation
Hope this helps.

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