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()
Related
I am building a mortgage calculator in Javascript. When the submit button is pressed nothing happens. I appear to have no errors in my HTML or Javascript.
function computeLoan() {
var amount = document.getElementById('amount').value;
var interest_rate =
document.getElementById('interest_rate').value;
var months = document.getElementById('months').value;
var interest = (amount * (interest_rate * .01)) / months;
var taxes = document.getElementById('taxes').value;
var insurance = document.getElementById('insurance').value;
var escrow = (taxes + insurance) / 12;
var loanPayment = amount * interest * (Math.pow(1 + interest,
months)) / (Math.pow(1 + interest, months) - 1);
var monthlyPayment = loanPayment + escrow;
monthlyPayment.toFixed(2);
monthlyPayment = document.getElementById('payment').value;
}
<form onsubmit="return computeLoan()" method="POST" action="javascript:;">
<table>
<tr>
<td class="labels">Loan Amount</td>
<td class="textbox"><input type="text" id="amount" min="1" max="10000000" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Mortgage Period (months)</td>
<td class="textbox"><input type="text" id="months" min="1" max="360" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Interest Rate</td>
<td class="textbox"><input type="text" id="interest_rate" min="0" max="100" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Property Taxes</td>
<td class="textbox"><input type="text" id="taxes" min="0" max="10000" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Homeowners Insurance</td>
<td class="textbox"><input type="text" id="insurance" min="0" max="10000" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Monthly Payment</td>
<td class="textbox"><input type="number" id="payment" name="payment"></td>
</tr>
<tr>
<td class="button"><input type="submit" id="calculate" name="calculate" onclick="computeLoan()"></td>
<td class="button"><input type="reset" name="Reset"></td>
</tr>
</table>
</form>
I expect the textbox for Monthly Payment to populate but nothing happens.
In the computeLoan function, the last line you assign the value of your calculated field #payment (which is an empty string at this point) to the value that you just calculated before.
What you want to do is assign the calculated value monthlyPayment to the value property of the input#payment element.
So revert the assignment in the last line
monthlyPayment = document.getElementById('payment').value;
should become
document.getElementById('payment').value = monthlyPayment;
Additionally you are also executing the function multiple times.
The onsubmit of the form executes the function
The onclick of the submit button executes the function
Considering the action of the form you are not submitting the form, so you could reduce the code to
function computeLoan() {
var amount = document.getElementById('amount').value;
var interest_rate =
document.getElementById('interest_rate').value;
var months = document.getElementById('months').value;
var interest = (amount * (interest_rate * .01)) / months;
var taxes = document.getElementById('taxes').value;
var insurance = document.getElementById('insurance').value;
var escrow = (taxes + insurance) / 12;
var loanPayment = amount * interest * (Math.pow(1 + interest,
months)) / (Math.pow(1 + interest, months) - 1);
var monthlyPayment = loanPayment + escrow;
monthlyPayment.toFixed(2);
document.getElementById('payment').value = monthlyPayment;
}
<form onsubmit="return false;">
<table>
<tr>
<td class="labels">Loan Amount</td>
<td class="textbox">
<input type="text" id="amount" min="1" max="10000000" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Mortgage Period (months)</td>
<td class="textbox">
<input type="text" id="months" min="1" max="360" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Interest Rate</td>
<td class="textbox">
<input type="text" id="interest_rate" min="0" max="100" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Property Taxes</td>
<td class="textbox">
<input type="text" id="taxes" min="0" max="10000" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Homeowners Insurance</td>
<td class="textbox">
<input type="text" id="insurance" min="0" max="10000" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Monthly Payment</td>
<td class="textbox">
<input type="number" id="payment" name="payment">
</td>
</tr>
<tr>
<td class="button">
<button id="calculate" name="calculate" onclick="computeLoan()">
Calculate
</button>
</td>
<td class="button">
<input type="reset" name="Reset">
</td>
</tr>
</table>
</form>
Note that the button is not a submit anymore. And that the form is prevented its default action on submit only.
Additionally you can make the computateLoan only compute something when all values are defined
function computeLoan() {
const amount = document.getElementById('amount').value;
const interest_rate = document.getElementById('interest_rate').value;
const months = document.getElementById('months').value;
// This `let result = value1 || value2` is similar to the trenary operator
// `let result = value1 ?: value2` you might know from other labguages
// `result` will evaluate to `value1` if that is not null or undefined,
// otherwise it will evaluate to `value2`
const taxes = document.getElementById('taxes').value || 0;
const insurance = document.getElementById('insurance').value || 0;
if (amount && interest_rate && months) {
let interest = (amount * (interest_rate * .01)) / months;
let escrow = (taxes + insurance) / 12;
let loanPayment = amount * interest * (Math.pow(1 + interest, months)) / (Math.pow(1 + interest, months) - 1);
let monthlyPayment = (loanPayment + escrow).toFixed(2);
document.getElementById('payment').value = monthlyPayment;
} else {
document.getElementById('payment').value = '';
}
}
See: https://codepen.io/anon/pen/ROENKW
function computeLoan() {
// rest of the function
var monthlyPayment = loanPayment + escrow;
monthlyPayment = monthlyPayment.toFixed(2);
document.getElementById('payment').value = monthlyPayment;
}
Hey please update the last two lines of the function by assigning the value of monthlyPayment to the element.
This will work :)
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>
I need to calculate totals and the discount amounts on the following table.
<tbody id="generate_invoice_table">
<tr>
<td>16</td>
<td>Glass Polish Normal</td>
<td><input type="text" class="form-control text-right quantity" value="1"></td>
<td class="price">8000.00</td><td><input type="text" class="form-control text-right discount"></td>
<td><input type="text" disabled="" class="form-control text-right amount"></td>
<td><input type="checkbox" checked="" name="check-invoice"></td>
</tr>
</tbody>
So basically, I want to enter quantity and then the discount and show the amount at the last input box.
The Javascript is given below, I get the message trs.find is not a function...
$('#invoice').delegate('.quantity,.price,.discount', 'keyup', function () {
var t = document.getElementById("generate_invoice_table");//find table data
var trs = t.getElementsByTagName("tr");
var qty = trs.find('.quantity').val();
var price = trs.find('.price').val();
var dis = trs.find('.discount').val();
varamt = (qty * price) - (qty * price * dis) / 100;
trs.find('.amount').val(amt);
total();//calculate total and show after the invoice table
});
});
function total() {
var t = 0;
$('.amount').each(function (i, e) {
varamt = $(this).val() - 0;
t += amt;
});
$('.total').html(t);
}
delete line with var t= and try to replace the next line whit this code:
var trs = $("#generate_invoice_table tr");
As was mentioned it's bettter to choso what you gonna use pure JS or jQuery. On example below there are onkeyup events on discount and quantity inputs. In event handler recalc() price, quantity and discount are read using document.getElementById selectors. The amount calculated and inserted into appropriate input.
amt count I took without changes.
function recalc() {
var price = Number(document.getElementById('price').innerText);
var quantity = Number(document.getElementById('quantity').value);
var discount = Number(document.getElementById('discount').value);
var total = '';
if (price && quantity) {
total = discount ? ((quantity * price) - (quantity * price * discount) / 100) : (quantity * price);
}
document.getElementById('amount').value = total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody id="generate_invoice_table">
<tr>
<td>16</td>
<td>Glass Polish Normal</td>
<td>
<input type="text" id="quantity" class="form-control text-right quantity" value="1" onkeyup="recalc()">
</td>
<td class="price">
<span id="price">8000.00</span>
</td>
<td>
<input type="text" id="discount" class="form-control text-right discount" onkeyup="recalc()">
</td>
<td>
<input type="text" disabled="" id="amount" class="form-control text-right amount">
</td>
<td>
<input type="checkbox" checked="" name="check-invoice">
</td>
</tr>
</tbody>
Hope this helps
I have table like below :
<table>
<thead>
<th>Product Type</th>
<th>Quantity</th>
<th>Unit</th>
<th>Total</th>
</thead>
<tr>
<td>Gas</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="30.42">Liter</option>
<option value="25.30">Ton</option>
<option value="45.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
<tr>
<td>Diesel</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="20.42">Liter</option>
<option value="18.30">Ton</option>
<option value="25.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
<tr>
<td>Fuel</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="30.42">Liter</option>
<option value="25.30">Ton</option>
<option value="45.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
I would like to calculate ( qty * unit ) each row based qty and unit and put the result total column.
At the end of the calculation, I want to sum whole total fields and put the Grand Total field.
I tried like below which is always returning NaN but when I checked the value by typeof returning number!!! :
$(document).ready(function() {
$('input[name^=qty], select[name^=unit]').change(function(){
var total = 0;
var $row = $(this).parent();
var qty = parseFloat($row.find('input[name=qty]').val());
var price = parseFloat($row.find("select[name='unit'] option:selected").val());
total = parseFloat(qty * price);
$row.find('.amount').text(parseFloat(qty * price));
})
});
There are several errors here, including using text() on an input field, and using parent() instead of closest("tr").
I've also added classes to your elements to make the selectors easier. Try this:
$('.qty, .unit').change(function(){
var total = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
var price = parseFloat($row.find(".unit").val());
total = parseFloat(qty * price);
$row.find('.total').val(parseFloat(qty * price));
})
Example fiddle
UPDATE
Added blank default to selects:
$('.qty, .unit').change(function(){
var total = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
var price = parseFloat($row.find(".unit").val());
total = qty * price;
if (isNaN(total)) {
$row.find('.total').val("");
}
else {
$row.find('.total').val(total);
}
})
Fiddle
Instead of var $row = $(this).parent(); try
var $row = $(this).closest("tr");
The code you have is looking at the td and you need to find the tr. Closest looks for the closest match up the DOM tree.
Try this,not tested
$(document).ready(function() {
$('input[name^=qty], select[name^=unit]').change(function(){
var total = 0;
var $row = $(this).parent().prev(); //changed here
var qty = parseFloat($row.find('input[name=qty]').val());
var price = parseFloat($row.find("select[name='unit'] option:selected").val());
total = parseFloat(qty * price);
$row.find('.amount').text(parseFloat(qty * price));
})
});
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);
}