I'm trying to add dynamic row of table in my code. And when I click on the add button it displays the incorrect row. It suppose to display the checkbox, dropdown and input text row instead of the header row. Below are the javascript and html code together with the incorrect output. Do I have to change the javascript code? I've also tried looking for the answer inside the web but I found nothing. Please help me thanks.
Javascript code:
<script>
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;
switch(newcell.childNodes[0].type){
case"select-one":newcell.childNodes[0].selectedIndex=0;
break;
case"checkbox":newcell.childNodes[0].checked=false;
break;
case"text":newcell.childNodes[0].value="";
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);}}
</script>
HTML Code :
<input type="button" value="Add More" onClick="addRow('dataTable')">
<input type="button" value="Delete" onClick="deleteRow('dataTable')">
<table id="dataTable" border="1">
<tr>
<th>✓</th>
<th> Relationship </th>
<th> Name </th>
<th> Occupation </th>
<th> Phone Number </th>
</tr>
<tr>
<td><input type="checkbox" name="chk"></td>
<td>
<select name="fam_relationship[]" id="fam_relationship">
<option value="">Select one</option>
<option value="Spouse">Spouse</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
</select>
</td>
<td><input type="text" name="fam_name[]" id="fam_name"> </td>
<td><input type="text" name="fam_occupation[]" id="fam_occupation"></td>
<td><input type="text" name="fam_phone[]" id="fam_phone"> </td>
</tr>
</table>
Output:
Replace 0 into 1 at the following line:
newcell.innerHTML=table.rows[1].cells[i].innerHTML;
up here rows[1] instead rows[0]
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[1].cells[i].innerHTML;
switch (newcell.childNodes[0].type) {
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "text":
newcell.childNodes[0].value = "";
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);
}
}
<input type="button" value="Add More" onClick="addRow('dataTable')">
<input type="button" value="Delete" onClick="deleteRow('dataTable')">
<table id="dataTable" border="1">
<tr>
<th>✓</th>
<th>Relationship</th>
<th>Name</th>
<th>Occupation</th>
<th>Phone Number</th>
</tr>
<tr>
<td>
<input type="checkbox" name="chk">
</td>
<td>
<select name="fam_relationship[]" id="fam_relationship">
<option value="">Select one</option>
<option value="Spouse">Spouse</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
</select>
</td>
<td>
<input type="text" name="fam_name[]" id="fam_name">
</td>
<td>
<input type="text" name="fam_occupation[]" id="fam_occupation">
</td>
<td>
<input type="text" name="fam_phone[]" id="fam_phone">
</td>
</tr>
</table>
Related
The output shown on image
Hi am not much expertise in javascript, In my code I have Add-Items & Delete-Items button which is working fine.First row works fine for total calculation function but rest of rows not working because of that Am not able to assign different names and ids for created row. How I can reuse javascript. Also please let me know how to receive data on submit using POST method or this code and how to find total amount of all rows I inserted at the bottom of table.
Thanks in Advance
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<script type="text/javascript" src="add_rows.js"></script>
<script>
function func()
{
var w = document.getElementById("qty").value;
var x = document.getElementById("price").value;
var z = document.getElementById("total");
z.value = Number(w)*Number(x);
}
</script>
</head>
<body>
<fieldset class="row2">
<legend>Catering Order Details</legend>
<p>
<input type="button" value="Add Items" onClick="addRow('dataTable')" />
<input type="button" value="Remove Items" onClick="deleteRow('dataTable')" />
</p>
<table id="dataTable" class="form" border="1">
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" /></td>
<td>
<label>Item</label>
<select size="1" name="Item[]" required="required" >
<?php
echo "<option value=''>---Choose Item---</option>";
$q=mysqli_query($dbConnect1,"SELECT DISTINCT ITEM as Item, ITEM_ID FROM `manage_item`");
while($r=mysqli_fetch_assoc($q))
{
$i=$r['ITEM_ID'];
$n=$r['Item'];
echo "<option value='$i'> $n</option>";
}
?>
</select>
</td>
<td>
<label>Quantity</label>
<input type="text" required="required" name="Qty[]" id="qty" value="">
</td>
<td>
<label>Price/Quantity</label>
<input type="text" required="required" name="Price[]" id="price" value="" onChange="func()">
</td>
<td>
<label>Total</label>
<input type="text" required="required" name="Total[]" id="total" value="">
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</body>
</html>
Here's my script
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 100){
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("Maximum items is 100.");
}
}
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) {
alert("Cannot Remove all the Items.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Instead to use IDs you may change them to class names like in:
<input type="text" required="required" name="Qty[]" class="qty" value="" oninput="func(this)">
Because you are using inline events you can:
use input event because the DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
this as parameter to the inline function: it will be the current element
Hence, change your func to:
function func(ele) {
var parentRow = ele.parentNode.parentNode;
var w = parentRow.querySelector('input.qty').value;
var x = parentRow.querySelector('input.price').value;
var z = parentRow.querySelector('input.total');
z.value = Number(w)*Number(x);
}
The this parameter now is the ele, current element. You can now get the parent row and using the classes and querySelector you can find all elements.
The snippet:
function updateGrandTotal() {
var gt = document.querySelector('input.grantotal');
gt.value = 0;
document.querySelectorAll('input.total').forEach(function(ele, idx) {
gt.value = +gt.value + +ele.value;
});
}
function func(ele) {
var parentRow = ele.parentNode.parentNode;
var w = parentRow.querySelector('input.qty').value;
var x = parentRow.querySelector('input.price').value;
var z = parentRow.querySelector('input.total');
z.value = Number(w)*Number(x);
updateGrandTotal();
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length -1;
if(rowCount < 100){
var row = table.insertRow(rowCount + 1);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}else{
alert("Maximum items is 100.");
}
}
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) {
alert("Cannot Remove all the Items.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
updateGrandTotal();
}
<fieldset class="row2">
<legend>Catering Order Details</legend>
<p>
<input type="button" value="Add Items" onClick="addRow('dataTable')" />
<input type="button" value="Remove Items" onClick="deleteRow('dataTable')" />
</p>
<table id="dataTable" class="form" border="1">
<thead>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<label>Grand Total</label>
<input type="text" required="required" name="Total[]" class="grantotal" value=""></td>
</tr>
</thead>
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" /></td>
<td>
<label>Item</label>
<select size="1" name="Item[]" required="required" >
<option value=''>---Choose Item---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>
<label>Quantity</label>
<input type="text" required="required" name="Qty[]" class="qty" value="" oninput="func(this)">
</td>
<td>
<label>Price/Quantity</label>
<input type="text" required="required" name="Price[]" class="price" value="" oninput="func(this)">
</td>
<td>
<label>Total</label>
<input type="text" required="required" name="Total[]" class="total" value="">
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
I'm nearing the end of this script and I've noticed an error.
It's possible to add rows to the table, however when I try to remove them it doesn't seem to work. I'm guessing the error is somewhere in my JS. It was working before and then stopped working all of a sudden! Can someone please shed some light on it?
Thanks,
Snelly
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LinePriceAfterDiscount = (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceAfterDiscount').value = LinePriceAfterDiscount.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY * (LINEPRICENET) - (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LinePriceAfterDiscount * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LinePriceAfterDiscount + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
/******Calculate totals*******/
//net
var arr = document.getElementsByName('LinePriceAfterDiscount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalNetAmount').value = tot;
//VAT
var arr = document.getElementsByName('TaxAmount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalTaxAmount').value = tot;
//Gross
var NetTotal = document.getElementById('TotalNetAmount').value;
var TaxTotal = document.getElementById('TotalTaxAmount').value;
GrossTotal = (+NetTotal + +TaxTotal);
document.getElementById('TotalGrossAmount').value = GrossTotal;
}
/******Adding and removing rows******/
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;
}
}
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 of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting">
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty 1|||</th>
<th>Line Price Net 2|||</th>
<th>Line Price Discount% 3|||</th>
<th>Line Price Discount Amount 4|||</th>
<th>Line Price With Discount 5|||</th>
<th>VAT Rate Amount 6|||</th>
<th>VAT Amount 7|||</th>
<th>Line Price Gross-OUTPUT 8|||</th>
</tr>
</thead>
<!-- start -->
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty[]" id="Qty" step="1" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<input type="number" name="LinePriceNet[]" step="0.01" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);" />
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount[]" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceAfterDiscount[]" id="LinePriceAfterDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);" />
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount[]" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput[]" id="GrossOutput">
</td>
</tr>
</table>
<table>
<tr>
<td><label>Net Amount</label>
<input readonly="readonly" type="number" name="TotalNetAmount[]" id="TotalNetAmount">
</td>
</tr>
<tr>
<td><label>VAT Amount</label>
<input readonly="readonly" type="number" name="TotalTaxAmount[]" id="TotalTaxAmount">
</td>
</tr>
<tr>
<td><label>Gross Amount</label>
<input readonly="readonly" type="number" name="TotalGrossAmount[]" id="TotalGrossAmount">
</td>
</tr>
</table>
</form>
</body>
</html>
Here are the code to work:
function deleteRow(tableID) {
debugger;
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].nextElementSibling;
if (chkbox != null && chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
For some reason childNodes[0] is text and childNodes[1] is the input you're looking for.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LinePriceAfterDiscount = (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceAfterDiscount').value = LinePriceAfterDiscount.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY * (LINEPRICENET) - (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LinePriceAfterDiscount * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LinePriceAfterDiscount + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
/******Calculate totals*******/
//net
var arr = document.getElementsByName('LinePriceAfterDiscount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalNetAmount').value = tot;
//VAT
var arr = document.getElementsByName('TaxAmount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalTaxAmount').value = tot;
//Gross
var NetTotal = document.getElementById('TotalNetAmount').value;
var TaxTotal = document.getElementById('TotalTaxAmount').value;
GrossTotal = (+NetTotal + +TaxTotal);
document.getElementById('TotalGrossAmount').value = GrossTotal;
}
/******Adding and removing rows******/
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;
}
}
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[1];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting">
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty 1|||</th>
<th>Line Price Net 2|||</th>
<th>Line Price Discount% 3|||</th>
<th>Line Price Discount Amount 4|||</th>
<th>Line Price With Discount 5|||</th>
<th>VAT Rate Amount 6|||</th>
<th>VAT Amount 7|||</th>
<th>Line Price Gross-OUTPUT 8|||</th>
</tr>
</thead>
<!-- start -->
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty[]" id="Qty" step="1" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<input type="number" name="LinePriceNet[]" step="0.01" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);" />
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount[]" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceAfterDiscount[]" id="LinePriceAfterDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);" />
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount[]" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput[]" id="GrossOutput">
</td>
</tr>
</table>
<table>
<tr>
<td><label>Net Amount</label>
<input readonly="readonly" type="number" name="TotalNetAmount[]" id="TotalNetAmount">
</td>
</tr>
<tr>
<td><label>VAT Amount</label>
<input readonly="readonly" type="number" name="TotalTaxAmount[]" id="TotalTaxAmount">
</td>
</tr>
<tr>
<td><label>Gross Amount</label>
<input readonly="readonly" type="number" name="TotalGrossAmount[]" id="TotalGrossAmount">
</td>
</tr>
</table>
</form>
</body>
</html>
I have created Dynamic Table for adding and deleting rows using HTML and JavaScript.
How to submit or export the dynamic data into excel sheet by using javaScript please give me help.
Here is my code..
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
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);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<INPUT type="button" value="Submit" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD>Employee Name</TD>
<TD><input type="text"name="ename"/></TD>
<TD>Employee Id</TD>
<TD><input type="text"name="eid"/></TD>
<TD>Employee Date of Joining</TD>
<TD><input type="date" name="edoj"/></TD>
<TD>Employee Designation</TD>
<TD>
<SELECT name="edesignation">
<OPTION value="aset">Assistant Software Engineer Trainee</OPTION>
<OPTION value="ase">Assistant Software Engineer</OPTION>
<OPTION value="asse">Assistant Systems Engineer</OPTION>
<OPTION value="asa">Assistant Systems Analyst</OPTION>
<OPTION value="ita">IT Analyst</OPTION>
<OPTION value="eng">Engineer</OPTION>
<OPTION value="se">Software Engineer</OPTION>
<OPTION value="sse">Systems Engineer</OPTION>
</SELECT>
</TD>
<TD>Employee Salary</TD>
<TD><input type="text"name="esalary"/></TD>
</TR>
</TABLE>
</BODY>
</HTML>
I am trying to remove checked row from dynamic user input table , but it never works. Here is the code
function addRow(tableID){
var table=document.getElementById(tableID);
var rowCount=table.rows.length;
if(rowCount<5){
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("Maximum number of extra data is 5.");
}
}
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) {
alert("Cannot remove all.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
<p>
<input type="button" value="Add Option" onClick="addRow('dataTable')"/>
<input type="button" value="Remove Option" onClick="deleteRow('dataTable')"/>
<table id="dataTable" >
<tbody>
<tr>
<p>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
<td>
<label>Name of Data:</label>
<input type="text" name="dataName">
</td>
<td>
<label>Data:</label>
<input type="text" name="data">
</td>
</p>
</tr>
</tbody>
</table>
The add function works fine, but delete function doesn't work. Could someone tell me what happened?
You almost done.
There are a few issues:
You have a blank space after <td> and before <input>. So, your <input> becomes as the second child:
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
It should be:
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
Otherwise, you can change childNodes[0] to childNodes[1].
Also, why do you have <p> before and after <td>? remove them.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 5) {
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("Maximum number of extra data is 5.");
}
}
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) {
alert("Cannot remove all.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
<input type="button" value="Add Option" onClick="addRow('dataTable')" />
<input type="button" value="Remove Option" onClick="deleteRow('dataTable')" />
<table id="dataTable">
<tbody>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td>
<label>Name of Data:</label>
<input type="text" name="dataName"> </td>
<td>
<label>Data:</label>
<input type="text" name="data"> </td>
</tr>
</tbody>
</table>
These are good answers, but better yet is to replace .childNodes[0] with .children[0] because you are only interested in elements, that way you don't have to worry about spaces and other sneaky stuff like that. You can read about it here : What is the difference between children and childNodes in JavaScript?
Made a change from
var chkbox = row.cells[0].childNodes[0];
to
var chkbox = row.cells[0].childNodes[1];
It is working now.
function addRow(tableID){
var table=document.getElementById(tableID);
var rowCount=table.rows.length;
if(rowCount<5){
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("Maximum number of extra data is 5.");
}
}
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[1];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot remove all.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
<p>
<input type="button" value="Add Option" onClick="addRow('dataTable')"/>
<input type="button" value="Remove Option" onClick="deleteRow('dataTable')"/>
<table id="dataTable" >
<tbody>
<tr>
<p>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td>
<label>Name of Data:</label>
<input type="text" name="dataName">
</td>
<td>
<label>Data:</label>
<input type="text" name="data">
</td>
</p>
</tr>
</tbody>
</table>
I need help in deleting the row one by one from the bottom of the table on clicking the delete row button.
Issue:
I have used the javascript function to delete a row from my table, instead of deleting the row one by one from the bottom it is getting deleted as a whole except the first 2 rows. I need to delete the rows from the bottom one by one except the first 2 rows when the delete button is clicked .
This is my code
<html>
<head>
<script type="text/javascript">
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[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
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=1; i<rowCount; i++) {
var row = table.rows[i];
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="pname"/></td>
<td><input type="text" name="qty"/></td>
<td><select name="brand"/>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
this help you :
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowDelete = table.rows.length - 1;
if (rowDelete > 1)
table.deleteRow(rowDelete);
else
alert("Cannot delete all the rows.")
}
catch(e) {
alert(e);
}
}
final code :
<html>
<head>
<script type="text/javascript">
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[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowDelete = table.rows.length - 1;
if (rowDelete > 1)
table.deleteRow(rowDelete);
else
alert("Cannot delete all the rows.")
}
catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="pname" value="" /></td>
<td><input type="text" name="qty" value=""/></td>
<td><select name="brand"/>
<select>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
Before going to the loop deleting the rows, you should check first the number of rows. or you can remove the loop since you are just deleting one row only which is the last row (rowCount-1);
Try this:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 2){
//for(var i =1; i < 2; i++) {
// var row = table.rows[i];
table.deleteRow(rowCount-1);
//}
}
else{
alert("Cannot delete all the rows.");
}
}
catch(e) {
alert(e);
}
}
Here is the working code, you didnt break the execution after deleting a row, thats why it was deleting all the rows
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];
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
else{
table.deleteRow(i);
rowCount--;
i--;
break;
}
}
}
catch(e) {
alert(e);
}
}
See if this Helps :
$('#tbl1').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#tbl1').append('<tr><td><input type="text" class="txtBox" /></td><td><input type="button" value="X" /></td></tr>')
});
Here is something to work with an HTML Snippet
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl1" style="border: 1px solid blue">
<tr>
<td>
<input type="text" class="txtBox" />
</td>
<td>
<input type="button" value="X" />
</td>
</tr>
</table>
<p>
<input type="button" value="Add">
</p>