Dynamic HTML Form - Javascript calculation errors - javascript

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.

Related

Add option Attribute to a selected row in a table in HTML

I have a table as below, in my table I can add new rows and select a row and delete it.
My problem is that I want to be able to select any row and add (select a color) attribute to it. with the below function I can add the option attribute but it adds it at the end of my table and not in the selected row. Can anyone help me solve this issue. Thanks!
This is my function to add a attribute to my row:
var selectionColor = 0
function addColor(tableID) {
var select = document.getElementById("color")
var clone = select.cloneNode(true)
var name = select.getAttribute("name") + selectionColor++
clone.id = name
clone.setAttribute("name", name)
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) {
table.appendChild(clone);
}
}
}catch(e) {
alert(e);
}
}
HTML part of my code:
<table id="Table">
<tr>
<th colspan="4" style="text-align: center;">Color Selection</th>
</tr>
<tr>
<th style="text-align: center;">Select</th>
<th style="text-align: center;">Color Selection</th>
<th style="text-align: center;">Quantity</th>
</tr>
<tr>
<td><input type="checkbox" name="chk"/></td>
<td id="des">
<select id="color" name="color">
<option disabled selected value>select a color</option>
<option value="wh">White</option>
<option value="blc">Black</option>
<option value="gry">Grey</option>
<option value="blu">Blue</option>
<option value="rd">Red</option>
</select>
</td>
<td><span id="fbskin-qty"></span></td>
</tr>
</table><br/>
<div class="button-div" style="text-align:center; margin:15px auto;">
<input type="button" value="Add a New Row" onclick="addRow('fbskinTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('fbskinTable')" />
<br/><br/>
<input type="button" value="Add A New Color" onclick="addColor('fbskinTable')" />
</div>
You are appending to the table when you should be appending to the cell.
Change:
table.appendChild(clone);
To:
row.cells[1].appendChild(clone);

Calculate sum of last column in dynamically added rows using javascript

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>

Calculate column on row add for all rows

I have developed a code to build out salary costs for a project. The problem is that only the first row is calculating.
I have searched and found a few forums discussing the same problem but every approach/code looks completely different. Also, I have copied whole coding examples from youtube videos/forums to replicate a solution and none seems to work. I know there may be issues with ID/class but being new to coding, everything just confuses me. Help!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name='vetCosting'>
<h3> Salaries </h3>
<table ID="salaries">
<tr>
<th>Classification</th>
<th>Hourly rate</th>
<th>Hours</th>
<th>Cost</th>
<th>Comments</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
<tr>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onFocus="startCalc();" onBlur="stopCalc()"></td>
<td><input type="number" name="salaryHours" value="" onFocus="startCalc();" onBlur="stopCalc()"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="ob_adRows.addRow(this)"></td>
<td><input type="button" value="-" ; onclick="ob_adRows.delRow(this)"></td>
</tr>
</table>
</form>
<script>
function startCalc() {
interval = setInterval("calc()", 2);
}
function calc() {
hrRate = document.vetCosting.hourlyRate.value;
salHours = document.vetCosting.salaryHours.value;
document.vetCosting.salaryCost.value = ((hrRate * 1) * (salHours * 1));
}
function stopCalc() {
clearInterval(interval);
}
</script>
<script>
function adRowsTable(id) {
var table = document.getElementById(id);
var me = this;
if (document.getElementById(id)) {
var row1 = table.rows[1].outerHTML;
function setIds() {
var tbl_id = document.querySelectorAll('#' + id + ' .tbl_id');
for (var i = 0; i < tbl_id.length; i++) tbl_id[i].innerHTML = i + 1;
}
me.addRow = function (btn) {
btn ? btn.parentNode.parentNode.insertAdjacentHTML('afterend', row1) :
table.insertAdjacentHTML('beforeend', row1);
setIds();
}
me.delRow = function (btn) {
btn.parentNode.parentNode.outerHTML = '';
setIds();
}
}
}
var ob_adRows = new adRowsTable('salaries');
</script>
</body>
</html>
I would like to be able to add and remove rows with calculations computing correctly for every row based on data inputs.
My first step would be to change your code from using setInterval() because that is running every 2 milliseconds even when there is no change in the input and the user is simply sitting there. I'd change it to a onKeyUp event that fires much less frequently.
That's done by simply changing your inputs to this:
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc();"></td>
So we get rid of the startCalc() and stopCalc() functions.
Now, once we have multiple rows, we need a way to identify each row. So we give your first row an id of 'row_0' and also pass it through your calc() functions as follows:
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_0');"></td>
We then update your calc() method to this, so that it can use each row individually:
function calc(id) {
var row = document.getElementById(id);
var hrRate = row.querySelector('input[name=hourlyRate]').value;
var salHours = row.querySelector('input[name=salaryHours]').value;
row.querySelector('input[name=salaryCost]').value = ((hrRate * 1) * (salHours * 1));
}
Next, upon clicking the buttons, this error is fired:
Uncaught ReferenceError: ob_adRows is not defined at HTMLInputElement.onclick
To change this, we'll change the function that you've written. Let's first prepare a template for each row, and then simply append it to the innerHTML of the table. However, this won't work because it will also refresh the entire table, hence wiping out data from our existing rows too. So we use this to make a new HTML node with of a row with the id 'row_x':
function newRowTemplate(rowCount) {
var temp = document.createElement('table');
temp.innerHTML = `<tr id='row_${rowCount}'>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp = "calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>`;
return temp.firstChild;
}
We directly make our new functions:
function addRow() {
var newRow = newRowTemplate(rowCount);
table.appendChild(newRow);
rowCount += 1;
}
function removeRow(el) {
el.parentNode.parentNode.remove();
rowCount -= 1;
}
And finally, we use these new functions in our original elements as follows:
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
Here's the final result:
function calc(id) {
var row = document.getElementById(id);
var hrRate = row.querySelector('input[name=hourlyRate]').value;
var salHours = row.querySelector('input[name=salaryHours]').value;
row.querySelector('input[name=salaryCost]').value = ((hrRate * 1) * (salHours * 1));
}
var table = document.getElementById('salaries');
var rowCount = 1;
function newRowTemplate(rowCount) {
var temp = document.createElement('table');
temp.innerHTML = `<tr id='row_${rowCount}'>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp = "calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>`;
return temp.firstChild;
}
function addRow() {
var newRow = newRowTemplate(rowCount);
table.appendChild(newRow);
rowCount += 1;
}
function removeRow(el) {
el.parentNode.parentNode.remove();
rowCount -= 1;
}
<body>
<form name="vetCosting">
<h3> Salaries </h3>
<h3> Salaries </h3>
<table id="salaries">
<tr>
<th>Classification</th>
<th>Hourly rate</th>
<th>Hours</th>
<th>Cost</th>
<th>Comments</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
<tr id="row_0">
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_0');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp="calc('row_0');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>
</table>
</form>
</body>
I just realized a bug in my code. Once row_x is created, and I delete and add another row, it'll create row_x again because the rowCount returns to x. You can fix this by removing the decrement in the remove row function.

How to show sell price when tax rate is added using javascript?

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 added and display in textbox?

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>

Categories