Dynamic HTML form not removing rows - Javascript error - javascript

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>

Related

how to find discount from total sum using javascript

I have a table that a user can dynamically add a row as needed. And as you can see underneath the table that is a sum of the last column's value which is dynamically added. I need to add two text boxes above the sum from that one textbox(name as discount) take input(as a number) from user and the second textbox(name as finalsum) display the output as the value(finalsum=sum-discount). and if the user does not give any input value then the discount should be initially zero. and the finalsum should be equal to sum
if you want more info let me know thank you! Any help will be greatly appreciated :)
<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;
if (rowCount < 4) {
// limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = "row_" + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.querySelectorAll("input, select");
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll("[name=qty]")[0].value;
var myBox3 = mainRow.querySelectorAll("[name^=sel]")[0].value;
var total = mainRow.querySelectorAll("[name=total]")[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1;
// calculate the totale of every total
var sumContainer = document.getElementById("totalOfTotals");
var totalContainers = document.querySelectorAll("[name=total]"),
i;
var sumValue = 0;
for (i = 0; i < totalContainers.length; ++i) {
sumValue += parseInt(totalContainers[i].value);
}
sumContainer.textContent = sumValue;
}
</script>
</head>
<body>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id="row_0">
<p>
<td>
<label>Quantity</label>
<input
type="number"
required="required"
name="qty"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="total">Total</label>
<input
type="text"
required="required"
class="small"
name="total"
/>
</td>
</p>
</tr>
</tbody>
</table>
<div>
<tr>
<span>Sum</span>
<span id="totalOfTotals">0</span>
</tr>
</div>
</body>
</html>
Solution Here !!!
<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;
if (rowCount < 4) {
// limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = "row_" + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.querySelectorAll("input, select");
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll("[name=qty]")[0].value;
var myBox3 = mainRow.querySelectorAll("[name^=sel]")[0].value;
var myBox4 = mainRow.querySelectorAll("[name=discount]")[0].value;
var total = mainRow.querySelectorAll("[name=total]")[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1-myBox4;
// calculate the totale of every total
var sumContainer = document.getElementById("totalOfTotals");
var totalContainers = document.querySelectorAll("[name=total]"),
i;
var sumValue = 0;
for (i = 0; i < totalContainers.length; ++i) {
sumValue += parseInt(totalContainers[i].value);
}
sumContainer.textContent = sumValue;
}
</script>
</head>
<body>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id="row_0">
<p>
<td>
<label>Quantity</label>
<input
type="number"
required="required"
name="qty"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="discount">Discount</label>
<input
type="text"
required="required"
class="small"
name="discount"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="total">Total</label>
<input
type="text"
required="required"
class="small"
name="total"
/>
</td>
</p>
</tr>
</tbody>
</table>
<div>
<tr>
<span>Sum</span>
<span id="totalOfTotals">0</span>
</tr>
</div>
</body>
</html>

I want a javascript code for cloning a select box in a table in html and not in JQuery

I am creating a bill page for my departmental store project. I need a javascript code to have a clone of my first row which I want to have select box to choose an ID for products and categories. I am not getting a correct select box instead a input text box(similiarly). So please help me out. I am new to this discussion. I am waiting for answers. Thank you!!!...
Here is my code
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
td {
width: 15px;
}
</style>
</head>
<body>
<div id="POItablediv">
<input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/>
<table id="POITable" border="1">
<tr>
<td>Product ID</td>
<td>Category ID</td>
<td>Price</td>
<td>Quantity</td>
<td>Number Of Products</td>
<td>Cart Price</td>
<td>Delete Product</td>
<td>Add Product</td>
<td>Calculate Cart Price</td>
</tr>
<tr>
<td>
<select id="pid" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td>
<td><input type="button" id="calculte" value="calculate" onclick="calculate(this)" /></td>
</tr>
<tr>
</tr>
</table>
<script>
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function calculate(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('lat').deleteRow(i);
}
function insRow() {
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var first = document.getElementById('pid');
var options = first.innerHTML;
var inp1=document.createElement('select');
var inp1 = new_row.cells[1].getElementsByTagName('select');
//inp1=document.createElement('select');
var options=inp1.innerHTML+options;
inp1.innerHTML=options;
alert(options);
alert(inp1);
/*
selectList.appendChild(option);
}*/
/* var all_select = document.getElementsById("pid");
alert(all_select);
new_row.cells[1].createElement("select");
for (i = 0; i < all_select.length; i++) {
var option = document.createElement("option");
option.value = all_select[i];
option.text = all_select[i];
}*/
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
alert("HELLO");
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
var inp5 = new_row.cells[5].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp6 = new_row.cells[6].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild(new_row);
}
</script>
</body>
</html>

To pass id and name through javascript

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>

javascript fields calculation of multiple fields

I am using this code this is html form where i need the javascript onblur calculation of qty * rate = amount
<div>
<p>
<input type="button" value="Add Product" onClick="addRow('dataTable')" />
<input type="button" value="Remove Product" onClick="deleteRow('dataTable')" />
</p>
<table style="width: 100%;" id="dataTable" class="responstable" border="1">
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="text" name="prod" maxlength="100" placeholder="Product *" required></td>
<td>
<input type="number" name="qty[]]" maxlength="10" placeholder="QUANTITY *" required>
</td>
<td>
<input type="number" step="0.01" name="rate[]" maxlength="10" placeholder="RATE *" required>
</td>
<td>
<input type="number" step="0.01" name="amt[]" placeholder="AMOUNT *" required>
</td>
</p>
</tr>
</tbody>
</table>
</div>
And this is Javascript code i am using for add input fields
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 25){ // limit the user from creating fields more than your limits
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 Limit is 25.");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Products.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
I need also auto calculation of total amount.
I know it is done by using input field id but here the problem is i don't know how to add different input field ID when i click add product here the same id comes on next input field so what is the best solution for this.
Try this fiddle for dynamic added elements jsfiddle.net/bharatsing/yv9op3ck/2/
HTML:
<div>
<p>
<input type="button" value="Add Product" id="btnAddProduct" />
<input type="button" value="Remove Product" id="btnRemoveProduct" />
<label>Total Amount:</label><label id="lblTotal">0</label>
</p>
<table style="width: 100%;" id="dataTable" class="responstable" border="1">
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="text" name="prod" maxlength="100" placeholder="Product *" required></td>
<td>
<input type="number" name="qty[]" maxlength="10" placeholder="QUANTITY *" required>
</td>
<td>
<input type="number" step="0.01" name="rate[]" maxlength="10" placeholder="RATE *" required>
</td>
<td>
<input type="number" step="0.01" name="amt[]" placeholder="AMOUNT *" required>
</td>
</p>
</tr>
</tbody>
</table>
</div>
Javascript/jQuery:
$("#btnAddProduct").click(function(){
addRow('dataTable');
});
$("#btnRemoveProduct").click(function(){
deleteRow('dataTable');
});
function CalculateAll(){
$('input[name="rate[]"]').each(function(){
CalculateAmount(this);
});
var total=0;
$('input[name="amt[]"]').each(function(){
total+= parseFloat($(this).val());
});
$("#lblTotal").html(total);
}
$(document).on("blur",'input[name="qty[]"]',function(){
CalculateAmount(this);
});
$(document).on("blur",'input[name="rate[]"]',function(){
CalculateAmount(this);
});
var totalAll=0;
function CalculateAmount(ctl){
var tr=$(ctl).parents("tr:eq(0)");
var qty=parseFloat($(tr).find('input[name="qty[]"]').val());
var rate=parseFloat($(tr).find('input[name="rate[]"]').val());
var amount=qty*rate;
$(tr).find('input[name="amt[]"]').val(amount);
if(!isNaN(amount)){
totalAll= totalAll + amount;
$("#lblTotal").html(totalAll);
}
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 25){ // limit the user from creating fields more than your limits
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 Limit is 25.");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Products.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
CalculateAll();
}
Since in your code you are only using JavaScript. Here is an attempt with JavaScript. You need not to have ID attribute only to calculate the total amount , you can give your amount element a class amount and use it to get sum on all the elements having this class.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 25){ // limit the user from creating fields more than your limits
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 Limit is 25.");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Products.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
function amount(event)
{
var rate =parseInt(event.target.value, 10);
var qty = parseInt(event.target.parentElement.previousElementSibling.querySelector("input").value, 10);
event.target.parentElement.nextElementSibling.querySelector("input").value = rate * qty;
}
function calculate()
{
var total = 0;
document.querySelectorAll(".amount").forEach(function(elem)
{
total = total + parseInt(elem.value,10);
});
alert(total);
}
<div>
<p>
<input type="button" value="Add Product" onClick="addRow('dataTable')" />
<input type="button" value="Remove Product"onClick="deleteRow('dataTable')" />
</p>
<table style="width: 100%;" id="dataTable" class="responstable" border="1">
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="text" name="prod" maxlength="100" placeholder="Product *" required></td>
<td>
<input type="number" name="qty[]]" maxlength="10" placeholder="QUANTITY *" required>
</td>
<td>
<input type="number" step="0.01" onBlur="amount(event)" name="rate[]" maxlength="10" placeholder="RATE *" required>
</td>
<td>
<input type="number" step="0.01" class ="amount" name="amt[]" placeholder="AMOUNT *" required>
</td>
</p>
</tr>
</tbody>
</table>
<button onClick="calculate()">Total</button>
</div>

Add Dynamic Row Table Not Displaying The Right Row

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>

Categories

Resources