Total price calculator logic difficulty - javascript

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

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 to calculating time difference

I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.
I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.
var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");
function calc(){
var minutt1=Number(hour1)*60+Number(min1);
var minutt2=Number(hour2)*60+Number(min2);
var resultat=0;
resultat = Number(minutt1) - Number(minutt2);
document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>
I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".
You need to get the value of hour1, min1, hour2, and min2. You also don't have an element min2:
var hour1=document.getElementById("hour1").value;
var min1=document.getElementById("min1").value;
var hour2=document.getElementById("hour2").value;
var min2=document.getElementById("min2").value;
What your code was trying to do was multiply and subtract HTML elements (never a good idea).
var hour1 = document.getElementById("hour1").value;
var min1 = document.getElementById("min1").value;
var hour2 = document.getElementById("hour2").value;
var min2 = document.getElementById("min2").value;
function calc() {
var minutt1 = Number(hour1) * 60 + Number(min1);
var minutt2 = Number(hour2) * 60 + Number(min2);
var resultat = 0;
resultat = Number(minutt1) - Number(minutt2);
document.getElementById("result").innerHTML = "Time differance is:" + Number(resultat);
}
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>
Other answers are close, but you need to get the value of the inputs after you click the button
var hour1 = document.getElementById("hour1");
var min1 = document.getElementById("min1");
var hour2 = document.getElementById("hour2");
var min2 = document.getElementById("min2");
window.calc = function () {
var minutt1 = parseInt(hour1.value) * 60 + parseInt(min1.value);
var minutt2 = parseInt(hour2.value) * 60 + parseInt(min2.value);
var resultat = minutt1 - minutt2;
document.getElementById("result").innerHTML = "Time differance is:" + resultat;
console.log({minutt1:minutt1,minutt2:minutt2,resultat:resultat,
hour1:hour1,min1:min1,
hour2:hour2,min2:min2
})
};
<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>
<div id="result"></div>

Code I have written for Burger, Coca and Salad price calculation doesn't work

I have written a code to calculate Burger, Coca and Salad price. The code should return a number (or a factor) based on the number or each ordered item. I can't figure out which part of the code is not right. it doesn't work when I change the number of items.
var BurgNum = document.getElementById('Bnum').value,
CocNum = document.getElementById('Cnum').value,
SalNum = document.getElementById('Snum').value,
Totalprice;
function getValue(n) {
return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
}
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);
Totalprice = XBurgNum * 10 + XCocNum * 5 + XSalNum * 4
document.getElementById('price').value = Totalprice;
<html>
How many Burgers you want to order? <input type="number" id="Bnum" value="0" onchange="getValue(n);"></input>
<br> How many Cocas you want to order? <input type="number" id="Cnum" value="0" onchange="getValue(n);"></input>
<br> How many Salads you want to order? <input type="number" id="Snum" value="0" onchange="getValue(n);"></input>
<br> Price: <input type="number" id="price" readonly="readonly"></input>
</html>
You are calling a function onchange which returns a value, but does nothing with it. Instead, your onchange function can get the values needed for the calculation and update the price accordingly.
var burg = document.getElementById('Bnum'),
coc = document.getElementById('Cnum'),
sal = document.getElementById('Snum'),
totalPrice = 0;
document.getElementById('price').value = totalPrice;
var updatePrice = function() {
var burgNum = burg.value,
cocNum = coc.value,
salNum = sal.value;
var xNums = [];
[burgNum, cocNum, salNum].forEach(function(n, i) {
xNums[i] = (n >= 2 && n < 5) ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
});
totalPrice = xNums[0]*10 + xNums[1]*5 + xNums[2]*4;
document.getElementById('price').value = totalPrice;
}
How many Burgers do you want to order?
<input type="number" id="Bnum" value ="0" onchange="updatePrice()"/><br>
How many Cocas do you want to order?
<input type="number" id="Cnum" value ="0" onchange="updatePrice()"/><br>
How many Salads do you want to order?
<input type="number" id="Snum" value="0" onchange="updatePrice()"/><br>
Price:
<input type="number" id="price" readonly="readonly"/>
That is because you are not calling right statement on 'onchange' event. You just call the getVAlue(n) function which does nothing except return a value that you also use for
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);
But you are not updating the output on change event.
Try this, It will help you...
function getValue(val)
{
var BurgNum = parseInt(document.getElementById('Bnum').value);
var CocNum = parseInt(document.getElementById('Cnum').value);
var SalNum = parseInt(document.getElementById('Snum').value);
BurgNum = (BurgNum>=2 && BurgNum<5)?BurgNum*0.9:(BurgNum<2)?BurgNum:BurgNum-1;
CocNum = (CocNum>=2 && CocNum<5)?CocNum*0.9:(CocNum<2)?CocNum:CocNum-1;
SalNum = (SalNum>=2 && SalNum<5)?SalNum*0.9:(SalNum<2)?SalNum:SalNum-1;
Totalprice = BurgNum*10 + CocNum*5 + SalNum*4;
document.getElementById('price').value = (Totalprice>0 && Totalprice!=='NaN')?Totalprice:0;
}
<html>
How many Burgers you want to order? <input type="number" id="Bnum" value ="0" onChange="getValue(this.value);"></input>
<br>
How many Cocas you want to order? <input type="number" id="Cnum" value ="0" onChange="getValue(this.value);"></input>
<br>
How many Salads you want to order? <input type="number" id="Snum" value="0" onChange="getValue(this.value);"></input>
<br>
Price: <input id="price" readonly="readonly"></input>
</html>
Happy Coding...

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 />

Using toFixed in the right place

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;
});

Categories