To pass id and name through javascript - 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>

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>

Dynamic HTML form not removing rows - Javascript error

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>

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>

Unexpected behavior manipulating dynamic user input table

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>

How to multiply and check the field of newly inserted row

I want to add new rows having 3 input field and check if multiplication of 2 field equals to third input field. But my problem is if I check the multiplication of first 2 input field, the result will effect second row and third row etc because they all have same id and user can add many rows.
How to check with different id or without effected. my some code are as follows:
function addRow(elem,id) {
var trElement = elem.parentElement.parentElement;
var tr = document.getElementsByTagName('tr');
tr = Array.prototype.slice.call(tr);
var a = tr.indexOf(trElement);
var b = a+1;
var table = document.getElementById('dataTable');
var j, m;
var rowCount = table.rows.length;
var row = table.insertRow(a);
var colCount = table.rows[b].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[b].cells[i].innerHTML;
}
}
<table width="100%" id="dataTable">
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
</table>
<input type="button" id="agri" value="Add Row" onclick="addRow(this,id)" />
Thanks in Advance
I hope it Help you ;
cheak result as :
function addRow(elem,id) {
var trElement = elem.parentElement.parentElement;
var tr = document.getElementsByTagName('tr');
tr = Array.prototype.slice.call(tr);
var a = tr.indexOf(trElement);
var b = a+1;
var table = document.getElementById('dataTable');
var j, m;
var rowCount = table.rows.length;
var row = table.insertRow(a);
var colCount = table.rows[b].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[b].cells[i].innerHTML;
}
}
function cheakMulti() {
r = document.getElementsByTagName('tr');
for (i = 0; i < r.length; i++)
{
if(r[i].children[2].children[0].value==r[i].children[1].children[0].value*r[i].children[0].children[0].value)
{
r[i].children[2].children[0].style.backgroundColor="green";
}
else
{
r[i].children[2].children[0].style.backgroundColor="red";
}
}
}
<table width="100%" id="dataTable">
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
</table>
<input type="button" id="agri" value="Add Row" onclick="addRow(this,id)" />
<input type="button" id="agri" value="Cheak" onclick="cheakMulti(this,id)" />

Categories

Resources