How to show sell price when tax rate is added using javascript? - 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>

Related

how to get table rows select option value using checkbox

I have the following html table with select option in one of the columns. I want to display the values of the rows that are checked but don't know how to work with the select option value. Can someone help me modify the code? If not using DOM, can we just use PHP to get all checked values and store in $ variable? Finally I will submit the checked values and insert into table using PHP. Thanks a lot.
<?php
require_once("connMysql.php");
$stu_add = mysqli_query($db_link, "SELECT * FROM stu");
$rowcount = mysqli_num_rows($stu_add);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>how to get options value in html table</title>
</head>
<body>
<table id="table" border="1">
<tr>
<th style="text-align:center; width:70px">Classname</th>
<th style="text-align:center; width:100px">Student ID</th>
<th style="text-align:center; width:100px">Name</th>
<th style="text-align:center; width:100px">Grade</th>
<th style="text-align:center; width:100px">Select</th>
</tr>
<?php
if($stu_add-> num_rows > 0 ){
while ($row = $stu_add-> fetch_assoc()){
?>
<tr>
<td id="classname" style="text-align:center;"><?php echo $row['classname'];?></td>
<td id="stuid" style="text-align:center;"><?php echo $row['stuid'];?></td>
<td id="stu_name" style="text-align:center;"><?php echo $row['stu_name'];?></td>
<td><select name="grade" id="grade">
<option value="">-Please select-</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</td>
<td align="center">
<input type="checkbox" id="checked" name="checked[]" value="<?php echo $row['stuid'];?>">
</td>
</tr>
<?php
}
}
?>
<input type="text" id="classname" size="10">
<input type="text" id="stuid" size="10">
<input type="text" id="stu_name" size="10">
<input type="text" id="grade" size="10">
<button class="" onclick="showData()">Show data</button>
</table>
<script>
function showData()
{
var table = document.getElementById('table');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// document.getElementById("classname").value = this.cells[0].innerHTML;
// document.getElementById("stuid").value = this.cells[1].innerHTML;
// document.getElementById("stu_name").value = this.cells[2].innerHTML;
// document.getElementById("grade").value = this.cells[3].innerHTML.options[0].text;
var a = this.cells[0].innerHTML;
var b = this.cells[1].innerHTML;
var c = this.cells[2].innerHTML;
var d = this.cells[3].innerHTML.options[0].text;
var data = a + b + c + d;
alert(data);
};
}
}
</script>
As the above user says you can get the id of the checkbox and use onchange then pass the value to the function.
```
$('#checkbox').change(function(){
var query = $(this).val();
showdata(query);
});
```

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.

Dynamic HTML Form - Javascript calculation errors

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.

Javascript form sum of form inputs

I have this form working almost perfect. If I apply discount to default price is changes, if I apply taxes it autofills too. But the last field with the sum of price after discount plus taxes is not working. Any idea?
Here is the code and a Fiddle
<html>
<body>
<table width="339" border="0" cellpadding="0">
<tr>
<td width="98">Taxes</td>
<td width="115">Discount</td>
<td width="118">Default price</td>
</tr>
<tr>
<td><select class="select" name="taxes" onChange="updateInput()">
<option value="no" selected>no taxes</option>
<option value="19">19% taxes</option> <!-- <====================== -->
</select></td>
<td><select class="select" name="discount" onChange="updateInput()">
<option value="0" selected>0% discount</option>
<option value="5">5% discount</option>
<option value="10">10% discount</option>
<option value="20">20% discount</option>
</select></td>
<td><input type="text" class="input140" name="cost" id="cost" value="1000"></td>
</tr>
<tr>
<td>Price after discount</td>
<td>Taxes</td>
<td>Total Price to pay</td>
</tr>
<tr>
<td><input type="text" name="price" value="1000"></td>
<td><input type="text" name="ttaxes" value="0"></td> <!-- <====================== -->
<td><input type="text" name="total" value="0"></td>
</tr>
</table>
<script type="text/javascript">
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
var taxes = document.getElementsByName("taxes")[0].value; // <======================
if ( isNaN( taxes ) ) // IF "no taxes" IS SELECTED...
document.getElementsByName("ttaxes")[0].value = 0;
else { cost = document.getElementsByName("price")[0].value;
document.getElementsByName("ttaxes")[0].value = (cost * (taxes / 100));
}
}
</script>
</body>
</html>
The Fiddle DEMO
https://jsfiddle.net/nte6xqdv/7/
I need the last field Total to pay to sum "Price after discount Taxes" automaticly but is not working
Thanks a lot
You may find it easier to identify the issues you are having if you separate out each part of the process.
If you store all of the elements you are going to be using at the beginning you will make your calculations easier to read plus avoid unnecessary DOM calls.
/**
* Elements
*/
var taxes = document.getElementsByName('taxes')[0];
var discount = document.getElementsByName('discount')[0];
var cost = document.getElementsByName('cost')[0];
var price = document.getElementsByName('price')[0];
var ttaxes = document.getElementsByName('ttaxes')[0];
var total = document.getElementsByName('total')[0];
/**
* Calculations
*/
function updateInput() {
price.value = cost.value - (cost.value * (discount.value / 100));
ttaxes.value = (price.value * (taxes.value / 100));
var sum = parseFloat(price.value) + parseFloat(ttaxes.value);
total.value = sum.toFixed(2);
}
/**
* Event Listeners
*/
taxes.addEventListener('change', updateInput);
discount.addEventListener('change', updateInput);
cost.addEventListener('change', updateInput);
cost.addEventListener('keyup', updateInput);
<table width="339" border="0" cellpadding="0">
<tr>
<td width="98">Taxes</td>
<td width="115">Discount</td>
<td width="118">Default price</td>
</tr>
<tr>
<td>
<select name="taxes" class="select">
<option value="0" selected>no taxes</option>
<option value="19">19% taxes</option>
</select>
</td>
<td>
<select name="discount" class="select">
<option value="0" selected>0% discount</option>
<option value="5">5% discount</option>
<option value="10">10% discount</option>
<option value="20">20% discount</option>
</select>
</td>
<td>
<input type="text" name="cost" class="input140" value="1000">
</td>
</tr>
<tr>
<td>Price after discount</td>
<td>Taxes</td>
<td>Total Price to pay</td>
</tr>
<tr>
<td><input type="text" name="price" value="1000"></td>
<td><input type="text" name="ttaxes" value="0"></td>
<td><input type="text" name="total" value="0"></td>
</tr>
</table>
I guess your problem is that two input are string, and you used + operator to concatenate them. It should be converted to a number to do add operation.
var total = document.getElementsByName("total")[0];
total.value = parseFloat(document.getElementsByName("price")[0].value) +
parseFloat(document.getElementsByName("ttaxes")[0].value);
https://jsfiddle.net/ssk7833/nte6xqdv/8/
function updateInput(){
var total = document.getElementsByName("total")[0];
var taxes = document.getElementsByName("ttaxes")[0].value;
var price = document.getElementsByName("price")[0].value;
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
var taxes = document.getElementsByName("taxes")[0].value; // <======================
if ( isNaN( taxes ) ) // IF "no taxes" IS SELECTED...
document.getElementsByName("ttaxes")[0].value = 0;
else { cost = document.getElementsByName("price")[0].value;
document.getElementsByName("ttaxes")[0].value = parseInt(cost * (taxes / 100));
}
total.value = parseInt(taxes * 10) + parseInt(price) || parseInt(price); //No NaNs
}
call updateInput whenever the input changes uses jQuery... jQuery is very simple to use, and learn, and every JavaScript programmer should know how to use it.
In jquery... invoke the change callback:
$("#inputFieldIdHere").change(updateInput())
What will this do?
This will do several things. It will:
Wait until the input field has changed whatever is inside
When the contents of the input field changes it will call the function: updateInput()

Calculate cheaper price by more quantity in javascript

I have created a form to calculate the price times the quantity of a item. It had more choices but I narrowed it down to one choice. But now I can't figure out how give price breaks for more quantity. Basically there are price breaks as follows:
Item A is 4.60 for 1+ item. For 10+ items 3.40, 25+ 2.68 and so on until it hits 5000+ items. This is the same for items, B and C except they are priced different.
How can I calculate this using the method below:
Html Form:
<form action="#" id="price-quote" onsubmit="return false">
<table width="501" border="0" cellpadding="10" cellspacing="20" style="padding- top:30px;">
<tr>
<th width="67" scope="row">Size:</th>
<td width="273" class="select-box"> <select id="size" name="size">
<option value="None">Select Size</option>
<option value="2.5 inches">2.5 inches</option>
<option value="3 inches">3 inches</option>
<option value="Oval">Oval</option>
</select>
</td>
</tr>
<tr>
<th scope="row">Quanitity:</th>
<td><input type="text" name="quantity" id="quantity" /></td>
</tr>
<tr>
<th scope="row"> </th>
<td><input class="button" type="button" value="Update" onmousedown="getTotal()"/></td>
</tr>
<tr>
<th> Price:</th>
<td><div id="totalPrice" style="float:right;"></div></td>
</tr>
</table>
</form>
Javascript:
var size_prices= new Array();
size_prices["None"]=0;
size_prices["2.5 inches"]=4.60;
size_prices["3 inches"]=4.90;
size_prices["Oval"]=5.10;
function getSizePrice()
{
var sizePrice;
var theForm = document.forms["price-quote"];
var selectedSize = theForm.elements["size"];
sizePrice = size_prices[selectedSize.value];
return sizePrice;
}
function getQuantity()
{
var theForm = document.forms["price-quote"];
//Get a reference to the TextBox
var quantity = theForm.elements["quantity"];
var howmany =0;
//If the textbox is not blank
if(quantity.value!="")
{
howmany = parseInt(quantity.value);
}
return howmany;
}
function getTotal()
{
var instantPrice = getSizePrice() * getQuantity();
document.getElementById('totalPrice').innerHTML =
"$"+instantPrice.toFixed(2);
}
Could someone please point me in the right direction. Thank you
function getTotal()
{
var q = getQuantity();
var unitPrice = 4.60;
if(q >= 10){
unitPrice = 3.40;
} else if (q >= 25){
unitPrice = 2.68;
}
var instantPrice = unitPrice * q;
document.getElementById('totalPrice').innerHTML =
"$"+instantPrice.toFixed(2);
}

Categories