I have a table that a user can dynamically add a row as needed. I need to add a text box underneath the table that will dynamically output the total of the last column using JavaScript. If the calculations can't be done dynamically then I can add a calculate button underneath the text box
<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;
}
</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>
</BODY>
</HTML>
Any help will be greatly appreciated.
Here try this.
I added the sum in a tfoot first but the way you added new row made it awkward so I just put it in a div at the bottom of the table.
<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>
I believe you want to get a total value of last column throughout the table.
Then I think you need to Iterate through column.
Using below function code.
function totalvalues() {
var table = document.getElementById("dataTable");
var totalcellvalue = 0;
for (var i = 0, row; row = table.rows[i]; i++) {
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//columns would be accessed using the "col" variable assigned in the for loop
if (j == 2) {
//alert('col html>>'+col.children[1].value);
totalcellvalue += parseInt(col.children[1].value);
}
}
}
console.log(totalcellvalue);
}
// And I have called the above method ```totalvalues()`` in your ```calculate()``` method.
<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;
totalvalues();// calling my function here
}
</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="number" required="required" class="small" name="total">
</td>
</p>
</tr>
</tbody>
</table>
</BODY>
</HTML>
Related
Hi guys can someone help me about my problem. The problem is when I put a value on the Buy Price and Tax rate column it didn't show the result on the sell price input box.
This my function
$(document).ready(function(){
function final_total(count){
var final_product_amount = 0;
for(j=1;j<=count;j++){
var quantity = 0;
var buy_price = 0;
var sell_price = 0;
var tax_rate = 0;
var total_amount = 0;
var total_sell = 0;
var actual_amount = 0;
var total_tax = 0;
var min_qty = 0;
quantity = $('#quantity'+j).val();
if(quantity>0){
buy_price = $('#buy_price'+j).val().replace(",","");
if(buy_price > 0 ){
total_amount = parseFloat(quantity) * parseFloat(buy_price);
$('#total_amount'+j).val('P '+total_amount);
tax_rate = $('#tax_rate'+j).val();
if(tax_rate>0){
total_sell = parseFloat(buy_price) * parseFloat(tax_rate)/100;
total_tax = parseFloat(buy_price) + parseFloat(total_sell);
$('#sell_price'+j).val('P '+total_tax);
}
}
actual_amount = $('#total_amount'+j).val().replace("P ","");
final_product_amount = parseFloat(final_product_amount) + parseFloat(actual_amount);
}
}
$('#final_total_amount').text('₱ '+final_product_amount);
}
}
I tried modifying the code but it did not show when I finished inputting some value on tax rate. When I clicked the + button and filling the input filled, the sell price on the first row is being filled and working. It only works when new table row is filled. Hope someone can help me about this one. Thanks.
Use onblur function to calculate selling price on both textbox buy_price and tax_rate.
onblur jquery api.
Below code snippet is to show how you can utilize the onblur function to calculate selling price and grand total amount.
function calculateSellPrice(_i) {
var _buyPrice = $("#txtBuyPrice-" + _i).val();
var _tax = $("#txtTax-" + _i).val();
var _sellPrice = 0;
if(_buyPrice != "" && _tax != "") {
_sellPrice = parseFloat(_buyPrice) + parseFloat(_tax);
$("#txtSellPrice-" + _i).val(_sellPrice);
}
calculateTotal();
}
function calculateTotal() {
var count = 2;
var totalAmount = 0;
for(var j=1; j<=count; j++) {
var sellingPrice = $("#txtSellPrice-" + j).val();
if(sellingPrice != "")
totalAmount += parseFloat(sellingPrice);
}
$("#lblGrandTotal").text("Grand Total: " + totalAmount);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table class="table table-bordered">
<thead>
<tr>
<td>Sl.No</td>
<td>Product</td>
<td>Buy Price</td>
<td>Tax</td>
<td>Sell Price</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select id="prod-1">
<option>Select</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
</td>
<td>
<input type="text" id="txtBuyPrice-1" value="" placeholder="Buy Price" onblur="calculateSellPrice(1);" />
</td>
<td>
<input type="text" id="txtTax-1" value="" placeholder="Tax" onblur="calculateSellPrice(1);" />
</td>
<td>
<input type="text" id="txtSellPrice-1" value="" placeholder="Sell Price" disabled />
</td>
</tr>
<tr>
<td>2</td>
<td>
<select id="prod-2">
<option>Select</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
</td>
<td>
<input type="text" id="txtBuyPrice-2" value="" placeholder="Buy Price" onblur="calculateSellPrice(2);" />
</td>
<td>
<input type="text" id="txtTax-2" value="" placeholder="Tax" onblur="calculateSellPrice(2);" />
</td>
<td>
<input type="text" id="txtSellPrice-2" value="" placeholder="Sell Price" disabled />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: right;">
<label id="lblGrandTotal">Grand Total: 0</label>
</td>
</tr>
</tfoot>
</table>
</body>
</html>
How to count 1 option selected in dropdown from different rows and display count in textbox?
I would like to count total value casualties of different rows and display count of total value casualties in textbox id injury.
Codes for dropdownlist && textbox && add row:
<select name="type" id="dd">
<option>Select a Type</option>
<option value="casualties">Casualties</option>
<option value="notcasualties">Not Casualties</option>
</select>
</select>
<label>Casualties:</label><input type="text" id="injury">
<btn><input type="button" value="addrow" onclick="addrow('dataTable2')" /></btn>
This codes are only able to display count = 1 in textbox id injury for the first row but not the added rows. I would like to total up count of value casualties after different rows are added. Could anyone help me.
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
Thanks in advance!
Add onchange="select($(this).val())" in select tag and following function in script
function select(value){
if(value==="casualties"){
$("#injury").val(parseInt($("#injury").val())+1);
}
else{
$("#injury").val(parseInt($("#injury").val())-1);
if($("#injury").val()<0)
$("#injury").val("0");
}
}
and remove
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
I made some changes that full fill your purpose
<html>
<head><title>table example</title></head>
<body>
<table id="dataTable2">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</TR>
<tr>
<td><input type="checkbox" name="checkbox[]"></td>
<TD><input type="text" name="id[]" id="id" /></TD>
<TD><input type="text" name="names[]" id="names"></TD>
<TD><input type="text" name="contacts[]" id="contacts" /> </TD>
<TD>
<select name="type" id="dd" class="selectpicker" data-style="select-with-transition" title="News Type" data-size="7" onchange="show()">
<option value="">Select a Type</option>
<option value="casualties" class="casualties-element">Casualties</option>
<option value="ncasualties">Non-Casualties</option>
<option value="witness">Witness</option>
</select>
</TD>
</tr>
</table>
<p>
<INPUT type="button" value="Add Row" onclick="addRow()" />
</p>
<table id="dataTable1" style="cellpadding:20px;">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</tr>
</table>
<p>
<label>No. of Casualties:</label>
<input type="text" name="injury" id="injury" class="injury span2" onClick="show();">
</p>
<script>
var count = 0;
function addRow() {
alert("test");
var table1 = document.getElementById('dataTable1');
var table = document.getElementById('dataTable2');
var did = document.getElementById('id').value;
var dname = document.getElementById('names').value;
var dcontact = document.getElementById('contacts').value;
var dddl = document.getElementById('dd');
var ddlvalue = dddl.options[dddl.selectedIndex].value;
if (ddlvalue == 'casualties') { count++; }
document.getElementById('injury').value = count;
var rowCount = table.rows.length;
//var row = table.insertRow(rowCount);
var row = table1.insertRow(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;
//alert(newcell.childNodes);
switch (i) {
case 0:
newcell.innerHTML = did;
break;
case 1:
newcell.innerHTML = dname;
break;
case 2:
newcell.innerHTML = dcontact;
break;
case 3:
newcell.innerHTML = ddlvalue;
break;
}
}
}
</script>
</body>
</html>
I'm currently working on an invoice project.
So far I have a dynamic form where you can add and remove rows (see snippet below).
However I have a problem with my javascript, I was wondering if someone could help me out with it.
Basically, when you input the values into the form on the first row, it calculates it all perfectly. However, if you add a new row and try to fill it in with some data, the javascript doesn't seem to perform any calculation for that row. It only works for the first row and it's really frustrating me! I can't seem to figure out why.
Any help is much appreciated. The snippet of code is below and you can run it and add some data to some rows to see for yourself. I need any advice I can get on this.
Thanks in advance guys.
Snelly
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate() {
var QTY = document.getElementById("Qty").value;
var LINEPRICENET = document.getElementById("LinePriceNet").value;
var LINEPRICEDISCOUNT = document.getElementById("LinePriceDiscountInput").value;
var TAXRATE = document.getElementById("TaxRate").value;
// Lineprice with discount
LINEPRICEWITHDISCOUNT = (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
document.getElementById('LinePriceWithDiscount').value = LINEPRICEWITHDISCOUNT.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY*(LINEPRICENET) - (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
document.getElementById("LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LINEPRICEWITHDISCOUNT * TAXRATE);
document.getElementById("TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LINEPRICEWITHDISCOUNT + TAXAMOUNT);
document.getElementById("GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
}
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</th>
<th>Line Price Net</th>
<th>Line Price Discount%</th>
<th>Line Price Discount Amount</th>
<th>Line Price With Discount</th>
<th>VAT Rate Amount</th>
<th>VAT Amount</th>
<th>Line Price Gross-OUTPUT</th>
</tr>
</thead>
<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" onchange="calculate();"/>
</td>
<td>
<input type="number" name="LinePriceNet" id="LinePriceNet" onchange="calculate();"/>
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate();"/>
<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="LinePriceWithDiscount" id="LinePriceWithDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate();"/>
<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>
</form>
</body>
</html>
I was able to fix it using following code. There might be cleaner version possible.
<!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
LINEPRICEWITHDISCOUNT = (QTY*(LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceWithDiscount').value = LINEPRICEWITHDISCOUNT.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 = (LINEPRICEWITHDISCOUNT * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LINEPRICEWITHDISCOUNT + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
}
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</th>
<th>Line Price Net</th>
<th>Line Price Discount%</th>
<th>Line Price Discount Amount</th>
<th>Line Price With Discount</th>
<th>VAT Rate Amount</th>
<th>VAT Amount</th>
<th>Line Price Gross-OUTPUT</th>
</tr>
</thead>
<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" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);"/>
</td>
<td>
<input type="number" name="LinePriceNet" 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="LinePriceWithDiscount" id="LinePriceWithDiscount">
</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>
</form>
</body>
</html>
The issue was, whenever you were hitting calculate function, it was taking values from first row only as there was no different ids for each rows. Here I used this to differentiate each row.
I had to use parentNode twice. If you find a cleaner version, please do share.
Also, using jQuery will make things easier.
This issue has probably a very simple solution, but as a beginner in Javascript, I can't find the solution after trying different possibilities.
So I have a form where people can reserve tickets at 6 or 10 Euros. Each line is a person. The user can add up to 5 people.
I wish to let the user see the total amount, depending of the ticket choice and the number of persons.
This is what I have:
HTML:
<form id="totaalBerekening" method="POST" action="example.php" role="form">
<table id="dataTable" class="form">
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chkbox[]" checked="checked" /></td>
<td>
<label>Voornaam</label>
<input type="text" required="required" name="vn[]">
</td>
<td>
<label>Naam</label>
<input type="text" required="required" name="naam[]">
</td>
<td>
<label>E-mail</label>
<input type="email" required="required" name="email[]">
</td>
<td>
<label>Telefoon</label>
<input type="text" required="required" name="tel[]">
</td>
<td>
<label>Type</label>
<select id="leeftijd" name="leeftijd[]" onchange="calculateTotal">
<option value="kind">Kind -12j (€ 6,00)</option>
<option value="volw">Volwassene (€ 10,00)</option>
</select>
</td>
<td>
<label>Shift</label>
<select name="shift[]">
<option value="shift1">11u30 - 13u00</option>
<option value="shift2">13u - 14u30</option>
</select>
</td>
<td><a class="kruisje" onClick="deleteRow('dataTable')">X</a></td>
</p>
</tr>
</tbody>
</table>
<p>Total price: <div id="totaalPrijs"></div></p>
<p>
<a type="button" class="simplebtn" onClick="addRow('dataTable')">Voeg nog een persoon toe</a>
</p>
<div class="clear"></div>
<input type="submit" class="submit" value="Bestel nu" />
</form>
Javascript:
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 5){ // 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("Opgelet, het maximum aantal tickets per persoon 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) { // limit the user from removing all the fields
alert("Opgelet, je kan niet alle personen verwijderen.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
var leeftijdPrijs = new Array();
leeftijdPrijs["kind"]=6;
leeftijdPrijs["volw"]=10;
function getLunchPrice()
{
var lunchPrice=0;
var theForm = document.forms["totaalBerekening"];
var selectedLeeftijd = theForm.elements["leeftijd"];
lunchPrice = leeftijdPrijs[selectedLeeftijd.value];
return lunchPrice;
}
function calculateTotal()
{
var totaalPrijs = getLunchPrice();
var divobj = document.getElementById('totaalPrijs');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the lunch $"+totaalPrijs;
}
</script>
I don't get an output on <div id="totaalPrijs">. What am I doing wrong?
I appreciate your help. Thanks in advance.
You forgot to put () at: onchange="calculateTotal()", so the function is never called. With that change, the total is shown when the user modify the "leeftijd" select box.
To compute total:
function getLunchPrice() {
var lunchPrice=0;
var theForm = document.forms["totaalBerekening"];
var selectedLeeftijd = theForm.elements;
for (var i=0; i < selectedLeeftijd.length; i++) {
var field = selectedLeeftijd[i];
if (field.name == "leeftijd[]") lunchPrice += leeftijdPrijs[field.value];
}
return lunchPrice;
}
Then add two calls to calculateTotal(): one in the addRow() function, another when the page is loaded, eventually nicer identifiers for the fields ;-)
I know there are like thousands of answers on Stack Overflow about this specific topic, but I have been reading them for 3 days and nights already trying to apply solutions to my code with no success.
The problem is that addRow works fine, but DeleteRow doesn't work at all.
Here is my HTML:
<input type="button" value="add" onClick="addRow('dataTable')" />
<input type="button" value="delete" onclick="deleteRow(this)"/>
<p></p>
</p>
</table>
<table id="dataTable" class="cv" border="1">
<tr>
<td>
<input type="text" style="width:100%" placeholder="ievadiet valodu">
</td>
<td>
<select id="BX_gender" name="BX_gender" required="required">
<option>dzimtā valoda</option>
<option>teicami</option>
<option>labi</option>
<option>viduvēji</option>
<option>pamatzināšanas</option>
</select>
</td>
<td>
<select id="BX_gender" name="BX_gender" required="required">
<option>teicami</option>
<option>labi</option>
<option>viduvēji</option>
<option>pamatzināšanas</option>
</select>
</td>
<td>
<select id="BX_gender" name="BX_gender" required="required">
<option>teicami</option>
<option>labi</option>
<option>viduvēji</option>
<option>pamatzināšanas</option>
</select>
</td>
</tr>
</table>
<div class="clear"></div>
</fieldset>
javascript:
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("Maksimālais ierakstu skaits ir 7.");
}
}
function DeleteRow(o) {
//no clue what to put here?
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
Here is a fiddle with code working (only the addRow function): http://jsfiddle.net/7AeDQ/690/
Assuming you want to delete the last row, you can use something like this
function deleteRow() {
var table = document.getElementById("dataTable");
var tbody = table.tBodies[0];
tbody.removeChild(tbody.lastChild);
}
Updated fiddle here
Using something like this, you don't need to traverse the DOM using parentNode.parentNode...