Using toFixed in the right place - javascript

I have a form which outputs a calculation from an input field and a drop down.
The script is fine apart from the grand total. When you type in a figure and select a value from the drop down, the grand total is rounded to 2 decimal places in the html.
Can anyone see why this is happening?
The form is below:
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1.50">Fast</option>
<option value="2.50">Medium</option>
<option value="3.50">Slow</option>
</select>
The javascript is below:
function updateCost()
{
var amount = parseFloat($('#amount').val()).toFixed(2);
var delivery = parseFloat($('#delivery').val()).toFixed(2);
var total = parseFloat(amount) + parseFloat(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var fixedrate = parseFloat(total / 100 * 8.2).toFixed(2);
var grandtotal = parseFloat(fixedrate) + parseFloat(total);
$("#grandtotal").html(grandtotal);
$("#total").html(total);
$("#fixedrate").html(fixedrate);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
$('#grandtotal').change(function(){ updateCost(); });
});

toFixed(2) should only be used in the part of the code that outputs it. In this case, you should have constructs like $("#someID").html(total.toFixed(2)), and remove the extra parseFloat()s. Something like this:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value),
delivery = parseFloat(document.getElementById("delivery").value),
total = amount + delivery,
fixedrate = total / 100 * 8.2,
grandtotal = fixedrate + total;
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
}
$(function(){
document.getElementById("amount").onchange =
document.getElementById("delivery").onchange = updateCost;
});

Related

Run javascript with value of field onload

Trying to have script run on page load with value of input on page load. The script runs onchange fine but I also want to run on page load. I have tried onload="calculateAmount(this.value);">
<input type="number" name="tot_pin_requested" id="tot_pin_requested" class="inputbox autowidth" value="{{ PPDEFAULT_VALUE }}" onchange="calculateAmount(this.value);">
<script>
function calculateAmount(val) {
var price = val * 1;
//display the result
var tot_price = price + (price * 0.029 + .30);
tot_price.toFixed(2);
var divobj = document.getElementById('amount');
divobj.value = tot_price;
}
</script>
Don't add it to the element, just have it separate:
<script>calculateAmount(document.querySelector("#tot_pin_requested").value);</script>
If you want to be sure the document is ready just use DOMContentLoaded event.
Also i suggest you use parseFloat on the inputValue so it's correctly changed from type string to type number. ( or parseInt(value, radix) if you will have just int values )
Also i don't know what is the logic behind var price = val * 1....
See below
window.addEventListener('DOMContentLoaded', (event) => {
const inputValue = document.getElementById('tot_pin_requested').value
calculateAmount(parseFloat(inputValue))
})
function calculateAmount(val) {
var price = val * 1;
//display the result
var tot_price = price + (price * 0.029 + .30);
tot_price.toFixed(2);
var divobj = document.getElementById('amount');
divobj.value = tot_price;
}
<input type="number" name="tot_pin_requested" id="tot_pin_requested" class="inputbox autowidth" value="10" onchange="calculateAmount(this.value);">
<input type="number" id="amount">

How can I calculate the total value of amount due after choosing different option from drop-down list?

I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.

How to calculate subtotal and total and show the result using jquery

I have a purshase form with two items.
the first item which is a number box who identify how many adults in the trip.
the second item which is a number box who identify how many seniors in the trip.
for example :
I want when I select 2 in the first number box, the subtotal next to the number box show me the result of the calculation ( price of one person * 2)
also for seniors section.
I found a code which is work with select and option value :
update_amounts();
$('select').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = (qty * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
I have edited this code to my needs like this :
$('input').change(update_amounts);
function update_amounts() {
var sum = 0.0;
$('#tickets > tbody > tr').each(function () {
var qty1 = $(this).find('#adults').val();
var qty2 = $(this).find('#senior').val();
var price = $(this).find('.price').text().replace(/[^\d.]/, '');
var amount = ((qty1+qty2) * price);
sum += amount;
$(this).find('.subtotal').text('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + amount);
});
$('#total').val('{{ \App\Helpers\Themes::getSymbolForCurrency() }}' + sum);
};
But it doesn't work!
this is the Html code :
<input type="number" name="adult_count" id="adults" min="0" required>
<input type="number" name="senior_count" id="seniors" min="0" required>
this image shows what I need :
https://i.ibb.co/52qzkh7/stack2.png

RealTime Calculations based on inputs and clicked radio buttons

I want to create a real time calculator for Net-Profit based on the trasaction, of the given quantity at given buy and sell price and it has 2 radio buttons as inputs.
What is happening is, I have to hit enter after putting values and selecting the button.
Where as what I want is, as soon as I input values and select radio button it should calculate the values.
Pl help me correct my code.
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Brokerage Calculator</title>
<head>
<script src="jquery-min.js"></script>
</head>
<body>
Buy Price
<input type="number" min="0" id="bp"><br />
Sell Price
<input type="number" min="0" id="sp"><br />
Qty:
<input type="number" min="0" id="qty"><br />
NSE:
<input name="exchname" id="nse" value="0.0000325" type="radio" checked="checked"><br />
BSE:
<input name="exchname" id="bse" value="0.0000275" type="radio"><br />
Turnover:
<span id="turnover">0</span><br />
Brokerage:
<span id="brokerage">0</span><br />
Security Transction Tax:
<span id="stt">0</span><br />
Total Tran Charges:
<span id="ttc">0</span><br />
SEBI Charges:
<span id="sebi">0</span><br />
Service Tax:
<span id="servtax">0</span><br />
Stamp Duty:
<span id="std">0</span><br />
Total Brokerage + Taxes:
<span id="ttx">0</span><br />
Net Profit:
<span id="pnl">0</span><br />
<script>
$('input').keyup(function(){ // run anytime the value changes
var buyPrice = parseFloat($('#bp').val()); // get value of field
var sellPrice = parseFloat($('#sp').val()); // convert it to a float
var quantity = parseFloat($('#qty').val());
var turnoverValue = (buyPrice + sellPrice) * quantity;
var sttValue = sellPrice * quantity * 0.025 / 100;
var sebiValue = turnoverValue * 0.0002 / 100;
var stdValue = 0.00002 * turnoverValue;
var excrate = document.querySelector('input[name="exchname"]:checked').value;
if(buyPrice<166.67){
var brkgbp = 0.05;
} else {
var brkgbp = buyPrice * 0.03 / 100;
}
if(sellPrice<166.67){
var brkgsp = 0.05;
} else {
var brkgsp = sellPrice * 0.03 / 100;
}
var brokerageValue = (brkgbp + brkgsp) * quantity;
var ttcValue = excrate * turnoverValue;
var servtaxValue = (brokerageValue + ttcValue + sebiValue) * 15 / 100;
var ttxValue = brokerageValue + sttValue + ttcValue + sebiValue + servtaxValue + stdValue;
var pnlValue = ((sellPrice - buyPrice) * quantity) - ttxValue;
$('#turnover').html(turnoverValue.toFixed(2));
$('#brokerage').html(brokerageValue.toFixed(2));
$('#stt').html(sttValue.toFixed(2));
$('#sebi').html(sebiValue.toFixed(2));
$('#servtax').html(servtaxValue.toFixed(2));
$('#ttc').html(ttcValue.toFixed(2));
$('#std').html(stdValue.toFixed(2));
$('#ttx').html(ttxValue.toFixed(2));
$('#pnl').html(pnlValue.toFixed(2));
});
<script>
</body>
</html>
Your closing script tag is missing the /, i.e. </script>
For your inputs, you're checking for the release of a keyboard key, which wouldn't fire for clicking radio buttons. Since you're checking to see if the value of the input has changed, you should change $('input').keyup to $('input').change.
edit: of course, you should do the NaN checking as well, as the other answers indicated - but the problem you described is solved by using the change event.
Didn't you forgot to close the script tag?
<script> ... </script>
Also, use
var buyPrice = parseFloat($('#bp').val()) || 0;
to initialize with a default value, so you don't get NaN
If you want the values to change when you reselect an option in the radio buttons, use:
function calculate(){ // run anytime the value changes
....
}
$('input').on('keyup', calculate);
$('input').on('click', calculate);
EDIT: I made a JSfiddle
https://jsfiddle.net/v3qd7b26/
Multiple issue in your code
1. You are missing the / in the script tag at the end. It should be </script> instead of <script>.
2. You need to ensure that the values entered are valid numbers only and then only proceed further, you can validate that using isNaN function in javascript
if(!isNaN(buyPrice) && !isNaN(sellPrice) && !isNaN(quantity)){
3.
Also, for checkbox need to add another selector. So you can create a common function and call it.
$("input").keyup(calculate);
$("input:checked").keyup(calculate);
Complete code:
$("input").keyup(calculate);
$("input:checked").keyup(calculate);
function calculate(){ // run anytime the value changes
var buyPrice = parseFloat($('#bp').val()); // get value of field
var sellPrice = parseFloat($('#sp').val()); // convert it to a float
var quantity = parseFloat($('#qty').val());
if(!isNaN(buyPrice) && !isNaN(sellPrice) && !isNaN(quantity)){
var turnoverValue = (buyPrice + sellPrice) * quantity;
var sttValue = sellPrice * quantity * 0.025 / 100;
var sebiValue = turnoverValue * 0.0002 / 100;
var stdValue = 0.00002 * turnoverValue;
var excrate = document.querySelector('input[name="exchname"]:checked').value;
if(buyPrice<166.67){
var brkgbp = 0.05;
} else {
var brkgbp = buyPrice * 0.03 / 100;
}
if(sellPrice<166.67){
var brkgsp = 0.05;
} else {
var brkgsp = sellPrice * 0.03 / 100;
}
var brokerageValue = (brkgbp + brkgsp) * quantity;
var ttcValue = excrate * turnoverValue;
var servtaxValue = (brokerageValue + ttcValue + sebiValue) * 15 / 100;
var ttxValue = brokerageValue + sttValue + ttcValue + sebiValue + servtaxValue + stdValue;
var pnlValue = ((sellPrice - buyPrice) * quantity) - ttxValue;
$('#turnover').html(turnoverValue.toFixed(2));
$('#brokerage').html(brokerageValue.toFixed(2));
$('#stt').html(sttValue.toFixed(2));
$('#sebi').html(sebiValue.toFixed(2));
$('#servtax').html(servtaxValue.toFixed(2));
$('#ttc').html(ttcValue.toFixed(2));
$('#std').html(stdValue.toFixed(2));
$('#ttx').html(ttxValue.toFixed(2));
$('#pnl').html(pnlValue.toFixed(2));
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Buy Price
<input type="number" min="0" id="bp"><br />
Sell Price
<input type="number" min="0" id="sp"><br />
Qty:
<input type="number" min="0" id="qty"><br />
NSE:
<input name="exchname" id="nse" value="0.0000325" type="radio" checked="checked"><br />
BSE:
<input name="exchname" id="bse" value="0.0000275" type="radio"><br />
Turnover:
<span id="turnover">0</span><br />
Brokerage:
<span id="brokerage">0</span><br />
Security Transction Tax:
<span id="stt">0</span><br />
Total Tran Charges:
<span id="ttc">0</span><br />
SEBI Charges:
<span id="sebi">0</span><br />
Service Tax:
<span id="servtax">0</span><br />
Stamp Duty:
<span id="std">0</span><br />
Total Brokerage + Taxes:
<span id="ttx">0</span><br />
Net Profit:
<span id="pnl">0</span><br />

Total price calculator logic difficulty

I have two number inputs, what I want to do is to get dynamially the total price.
The problem is that when I decrease the number its still adding and doesn't work correctly. Actually my brain cannot imagine any way to code it correctly. Could someone give me any clue please?
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0
$('#open').on("change", function() {
totalPrice = totalPrice + ($("#open").val() * openPrice);
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPrice = totalPrice + ($("#vip").val() * vipPrice);
$("#doZaplaty").html(totalPrice);
});
</script>
Because totalPrice = totalPrice + ($("#open").val() * openPrice); will add up previous result, as I commented.
However, you have 2 different total to take into account, so it's not easy to keep the state with only one total, because you need to subtract the previous result ,or calculate the change from previous value.
Instead, you can have 2 different total, like openTotal for result on #open and vipTotal on result for #vip, then you can use openTotal = ($("#open").val() * openPrice); to get the current state. And when you need to output the result, use $("#doZaplaty").html(openTotal + vipTotal); to show the final total.
var vipPrice = 290;
var openPrice = 80;
var openTotal = 0;
var vipTotal = 0;
$('#open').on("change", function() {
// As the totals are separated, we just need to get its current values computed.
openTotal = ($("#open").val() * openPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
$('#vip').on("change", function() {
vipTotal = ($("#vip").val() * vipPrice);
$("#doZaplaty").html(openTotal + vipTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Because you always add to totalPrice. Try this instead (untested):
<script>
var totalPrice = 0
function GetTotalPrice(vipNum,openNum){
var vipPrice = 290;
var openPrice = 80;
var total = vipNum * vipPrice + openNum * openPrice;
return total;
}
$('#open').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function(){
totalPrice = GetTotalPrice($("#vip").val(),$("#open").val());
$("#doZaplaty").html(totalPrice);
});
</script>
Please tyr by this simple way
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<input type="number" name="open" id='open' min="0" max="20">
<input type="number" name="vip" id='vip' min="0" max="20">
Set 2 hidden fields to store temp calculation value
<input type="hidden" name="totalPriceopenTemp" id='totalPriceopenTemp' value="0">
<input type="hidden" name="totalPricevipTemp" id='totalPricevipTemp' value="0">
<p> Total Price: <span id='doZaplaty'>0</span> EURO</p>
<script>
var vipPrice = 290;
var openPrice = 80;
var totalPrice = 0;
var totalPriceopenTemp = 0;
var totalPricevipTemp = 0;
$('#open').on("change", function() {
totalPriceopenTemp = ($("#open").val() * openPrice);
$("#totalPriceopenTemp").val(totalPriceopenTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
$('#vip').on("change", function() {
totalPricevipTemp = ($("#vip").val() * vipPrice);
$("#totalPricevipTemp").val(totalPricevipTemp);
totalPrice = parseInt($("#totalPriceopenTemp").val())+parseInt($("#totalPricevipTemp").val());
$("#doZaplaty").html(totalPrice);
});
</script>
I think It will work for you

Categories