javascript multiply 2 number show total and gtotal but show only one value? - javascript

I am using javascript calculation. multiply 2 numbers: number 1 * number 2 = total and how g-total but working only one value display?
I have need number 1 * number 2 = total and show Gtotal so please help and share a valuable idea...
HTML
<input
name="per_hour"
id="per_hour"
class="form-control"
value=""
onblur="perhour()"
placeholder="0"
/>
<input
name="per_hour_x"
id="per_hour_x"
class="form-control"
onblur="perhour()"
value=""
placeholder="0.00"
/>
Total
<input
name="per_hour_total"
id="per_hour_total"
class="form-control"
value=""
placeholder="0.00"
/>
G-Total
<input
type="text"
class="form-control total-fare"
id="total"
disabled
value="<?= $booking->total_fare ?>"
/>
<script>
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$("#per_hour_total").val(totaperhour).toFixed(2); //working
$("#total").val(totalamt).toFixed(2); //not working
}
</script>

It should be $('#per_hour_total').val(totaperhour.toFixed(2)); and not $('#per_hour_total').val(totaperhour).toFixed(2);
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$('#per_hour_total').val(totaperhour.toFixed(2));
$('#total').val(totalamt.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
total
<input type="text" class="form-control total-fare" disabled id="total" value="">
</div>
<div>
per_hour
<input name="per_hour" id="per_hour" class="form-control" value="" onblur="perhour()" placeholder="0">
</div>
<div>
per_hour_x
<input name="per_hour_x" id="per_hour_x" class="form-control" onblur="perhour()" value="" placeholder="0.00">
</div>
<div>
per_hour_total
<input name="per_hour_total" id="per_hour_total" class="form-control" value="" placeholder="0.00">
</div>

Related

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

Javascript removes the decimals when adding numbers together

I have this script that adds the 4 numbers together but JS doesn't take into account the original decimal places.
// Initial input form
<form class="weight_form" data-ajax="false" method="post">
<input type="text" class="input_save" placeholder="save as.."/>
<input type="text" id="lf" placeholder="enter LF lbs" value="" onkeyup="myFunction()"/>
<input type="text" id="rf" placeholder="enter RF lbs" value="" onkeyup="myFunction()"/>
<input type="text" id="lr" placeholder="enter LR lbs" value="" onkeyup="myFunction()"/>
<input type="text" id="rr" placeholder="enter RR lbs" value="" onkeyup="myFunction()"/>
<input type="submit" id="sub_save" value="save"/>
// Section to display results
<div id="bottom_section">
<input type="text" id="total" value=""/>
<input type="text" id="cross" value=""/>
<input type="text" id="ls" value=""/>
<input type="text" id="bite" value=""/>
</div>
// JS script to perform action on the fly
<script>
function myFunction() {
var lf = document.getElementById("lf");
var rf = document.getElementById("rf");
var lr = document.getElementById("lr");
var rr = document.getElementById("rr");
var lf = parseInt(lf.value);
var rf = parseInt(rf.value);
var lr = parseInt(lr.value);
var rr = parseInt(rr.value);
var lf_1 = lf*1;
var rf_1 = rf*1;
var lr_1 = lr*1;
var rr_1 = rr*1;
var total = lf_1 + rf_1 + lr_1 + rr_1;
var cross = rf_1 + lr_1 / total;
var ls = lf_1 + lr_1 / total;
var bite = lr_1 - rr_1;
$('#total').val(total);
$('#cross').val(Math.round(cross));
$('#ls').val(Math.round(ls));
$('#bite').val(bite);
};
</script>
If I enter say 20.5 for each input in the "weight_form" (lf, rf, lr, rr) the total is 80 instead of 82. Why does it seem to always round down the value?
To handle floats in your form, use parseFloat instead of parseInt, when parsing your values from the input elements.
Since you're using jQuery, you can simplify myFunction by selecting your fields and parse their values in one line:
var lf = parseFloat($("#lf").val());
var rf = parseFloat($("#rf").val());
var lr = parseFloat($("#lr").val());
var rr = parseFloat($("#rr").val());
Example:
function myFunction() {
var lf = parseFloat($("#lf").val());
var rf = parseFloat($("#rf").val());
var lr = parseFloat($("#lr").val());
var rr = parseFloat($("#rr").val());
var lf_1 = lf * 1;
var rf_1 = rf * 1;
var lr_1 = lr * 1;
var rr_1 = rr * 1;
var total = lf_1 + rf_1 + lr_1 + rr_1;
var cross = rf_1 + lr_1 / total;
var ls = lf_1 + lr_1 / total;
var bite = lr_1 - rr_1;
$('#total').val(total);
$('#cross').val(Math.round(cross));
$('#ls').val(Math.round(ls));
$('#bite').val(bite);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form class="weight_form" data-ajax="false" method="post">
<input type="text" class="input_save" placeholder="save as.." />
<input type="text" id="lf" placeholder="enter LF lbs" value="" onkeyup="myFunction()" />
<input type="text" id="rf" placeholder="enter RF lbs" value="" onkeyup="myFunction()" />
<input type="text" id="lr" placeholder="enter LR lbs" value="" onkeyup="myFunction()" />
<input type="text" id="rr" placeholder="enter RR lbs" value="" onkeyup="myFunction()" />
<input type="submit" id="sub_save" value="save" />
<div id="bottom_section">
<input type="text" id="total" value="" />
<input type="text" id="cross" value="" />
<input type="text" id="ls" value="" />
<input type="text" id="bite" value="" />
</div>
</form>

Javascript to calculate input figures from form input

I am trying to create a javascript that calculates the sum of 4 amounts, that is generated from the input fields.
The problem is, I want the Total Invoice Value to start reflecting the value after the user has inputted the Rate 1 and Amount 1 has shown. But it doesnt happen until all the 4 amounts have been generated. The Total Invoice Value reflect only after I input the amount in Rate 4.
The complete code I am working with right now is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="register" id="myForm" enctype="multipart/form-data" action="register" method="POST">
Qty 1:<input type="number" step="any" name="Qty1" autocomplete="off" id="Qty1" required><br>
Rate 1:<input type="number" step="any" name="Rate1" autocomplete="off" id="Rate1" class="rate" required><br>
Amount 1:<input readonly type="number" step="any" name="Amt1" autocomplete="off" id="Amt1" required><br><br>
Qty 2:<input type="number" step="any" name="Qty2" autocomplete="off" id="Qty2" required><br>
Rate 2:<input type="number" step="any" name="Rate2" autocomplete="off" id="Rate2" class="rate" required><br>
Amount 2:<input readonly type="number" step="any" name="Amt2" autocomplete="off" id="Amt2" required><br><br>
Qty 3:<input type="number" step="any" name="Qty3" autocomplete="off" id="Qty3" required><br>
Rate 3:<input type="number" step="any" name="Rate3" autocomplete="off" id="Rate3" class="rate" required><br>
Amount 3:<input readonly type="number" step="any" name="Amt3" autocomplete="off" id="Amt3" required><br><br>
Qty 4:<input type="number" step="any" name="Qty4" autocomplete="off" id="Qty4" required><br>
Rate 4:<input type="number" step="any" name="Rate4" autocomplete="off" id="Rate4" required><br>
Amount 4:<input readonly type="number" step="any" name="Amt4" autocomplete="off" id="Amt4" required><br><br>
Total Invoice Value:<input readonly type="number" step="any" name="TotalInvoiceValue" id="TotalInvoiceValue" pattern=".{1,}" autocomplete="off" required><br>
</form>
<script>
$('#Rate1').keyup(function(){
var Qty1;
var Rate1;
textone = parseFloat($('#Qty1').val());
texttwo = parseFloat($('#Rate1').val());
var result = textone * texttwo;
$('#Amt1').val(result.toFixed(2));
});
$('#Rate2').keyup(function(){
var Qty2;
var Rate2;
textone = parseFloat($('#Qty2').val());
texttwo = parseFloat($('#Rate2').val());
var result = textone * texttwo;
$('#Amt2').val(result.toFixed(2));
});
$('#Rate3').keyup(function(){
var Qty3;
var Rate3;
textone = parseFloat($('#Qty3').val());
texttwo = parseFloat($('#Rate3').val());
var result = textone * texttwo;
$('#Amt3').val(result.toFixed(2));
});
$('#Rate4').keyup(function(){
var Qty4;
var Rate4;
textone = parseFloat($('#Qty4').val());
texttwo = parseFloat($('#Rate4').val());
var result = textone * texttwo;
$('#Amt4').val(result.toFixed(2));
});
$('#Rate4').keyup(function(){
var Amt1;
var Amt2;
var Amt3;
var Amt4;
textone = parseFloat($('#Amt1').val());
texttwo = parseFloat($('#Amt2').val());
textthree = parseFloat($('#Amt3').val());
textfour = parseFloat($('#Amt4').val());
var result = textone + texttwo + textthree + textfour;
$('#TotalInvoiceValue').val(result.toFixed(2));
});
</script>
I tried to get the javascript to start taking totals from rate 1 itself by adding multiple element name in the #TotalInvoiceValue function like this:
$('#Rate1, #Rate2, #Rate3, #Rate4').keyup(function(){
var Amt1;
var Amt2;
var Amt3;
var Amt4;
textone = parseFloat($('#Amt1').val());
texttwo = parseFloat($('#Amt2').val());
textthree = parseFloat($('#Amt3').val());
textfour = parseFloat($('#Amt4').val());
var result = textone + texttwo + textthree + textfour;
$('#TotalInvoiceValue').val(result.toFixed(2));
});
But it still doesn't work.
I also tried assiging same class to all the Rate inputs like this:
html
<input id="Rate1" class="rate" type="text">
<input id="Rate2" class="rate" type="text">
<input id="Rate3" class="rate" type="text">
<input id="Rate4" class="rate" type="text">
javascript
$('.rate').on('keyup', function() {
let result = 0;
$('.rate').each(function() { result += parseFloat(this.value); });
$('#TotalInvoiceValue').val(result.toFixed(2));
})
And even this is not working for me. Please help.
In the Demo the following was used:
HTMLFormControlsCollection API
<input type="number">
<output></output>
oninput On-event Property
Event Delegation
Note: This is pure JavaScript.
If each input and output element has an initial value:
<input id="N0" type="number" value="0">
...
<input id="N*" type="number" value="0">
<output id="T0">0</output>
Then expressions like this will always be displayed as a number which is important if your event handler listens on an event that has an immediate reaction (ex. input, keypress, etc):
T0.value = N0.valueAsNumber + N1.valueAsNumber + ...N(N).valueAsNumber
Even though the only input the user uses was N0 at the time, N1 thu N(N) is still included in expression because they started off with value="0".
Demo
var sum = document.forms.sum;
var f = sum.elements;
var n0 = f.N0;
var n1 = f.N1;
var n2 = f.N2;
var n3 = f.N3;
var t0 = f.T0;
sum.oninput = add;
function add(e) {
if (e.target.className === "N") {
t0.value = n0.valueAsNumber + n1.valueAsNumber + n2.valueAsNumber + n3.valueAsNumber;
} else {
return false;
}
return false;
}
input {
font: inherit;
display: block;
width: 6ch
}
<form id='sum'>
<input id='N0' type='number' class='N' value='0'>
<input id='N1' type='number' class='N' value='0'>
<input id='N2' type='number' class='N' value='0'>
<input id='N3' type='number' class='N' value='0'>
<output id='T0'>0</output>
</form>
JSFiddle Example
https://jsfiddle.net/o2gxgz9r/47359/
HTML
<div>
Value 1: <input class="val" id="val1">
<br/>
Value 2: <input class="val" id="val2">
<br/>
Value 3: <input class="val" id="val3">
<br/>
Value 4: <input class="val" id="val4">
<br/>
Result: <input class="result">
</div>
JS
$(document).ready(function() {
var handleChange = function() {
var result = 0;
var setResult = true;
$(".val").each(function(){
if($(this).val() > 0) {
result += parseInt($(this).val());
} else {
setResult = false;
}
})
$(".result").val(setResult ? result : '');
};
$(".val").change(handleChange);
});
Thanks for all of your answers. Using your suggestions, this is how my problem got fixed:
HTML:
<form name="register" id="myForm" enctype="multipart/form-data" action="register" method="POST">
Qty :<input type="number" step="any" name="Qty1" autocomplete="off" id="Qty1" required><br>
Rate:<input type="number" step="any" name="Rate1" autocomplete="off" id="Rate1" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt1" autocomplete="off" id="Amt1" class="amt" required><br><br>
Qty :<input type="number" step="any" name="Qty2" autocomplete="off" id="Qty2" required><br>
Rate:<input type="number" step="any" name="Rate2" autocomplete="off" id="Rate2" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt2" autocomplete="off" id="Amt2" class="amt" required><br><br>
Qty :<input type="number" step="any" name="Qty3" autocomplete="off" id="Qty3" required><br>
Rate:<input type="number" step="any" name="Rate3" autocomplete="off" id="Rate3" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt3" autocomplete="off" id="Amt3" class="amt" required><br><br>
Qty :<input type="number" step="any" name="Qty4" autocomplete="off" id="Qty4" required><br>
Rate:<input type="number" step="any" name="Rate4" autocomplete="off" id="Rate4" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt4" autocomplete="off" id="Amt4" class="amt" required><br><br>
JAVASCRIPT:
$('#Rate1').keyup(function(){
var Qty1;
var Rate1;
textone = parseFloat($('#Qty1').val());
texttwo = parseFloat($('#Rate1').val());
var result = textone * texttwo;
$('#Amt1').val(result.toFixed(2));
});
$('#Rate2').keyup(function(){
var Qty2;
var Rate2;
textone = parseFloat($('#Qty2').val());
texttwo = parseFloat($('#Rate2').val());
var result = textone * texttwo;
$('#Amt2').val(result.toFixed(2));
});
$('#Rate3').keyup(function(){
var Qty3;
var Rate3;
textone = parseFloat($('#Qty3').val());
texttwo = parseFloat($('#Rate3').val());
var result = textone * texttwo;
$('#Amt3').val(result.toFixed(2));
});
$('#Rate4').keyup(function(){
var Qty4;
var Rate4;
textone = parseFloat($('#Qty4').val());
texttwo = parseFloat($('#Rate4').val());
var result = textone * texttwo;
$('#Amt4').val(result.toFixed(2));
});
$('.rate').on('keyup', function() {
var result = 0;
var setResult = true;
$('.amt').each(function() {
if($(this).val() > 0) {
result += parseFloat(this.value);
}
});
$('#TotalInvoiceValue').val(result.toFixed(2));
});

How to display recommendations after calculating a certain result?

How do I display something like a recommendation list after a user calculate a result from the inputs? E.g having the user to key in the salaries of the family and calculating the PCI (Per capita income) and after they key in and press on the calculate button which then will trigger a list of recommendations based on the amount of PCI the family have (Maybe tables that shows different results based on different categories of PCI?)
<!DOCTYPE html>
<html>
<head>
<script src="common.js"></script>
<script>
function cal()
{
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var total = (parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
document.getElementById('total').value = total;
alert (total);
}
</script>
</head>
<body>
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" value="" placeholder="Enter your 4th family income..."/>
<input id="members" value="" placeholder="Enter the total number of family members..."/>
<br>
<button onclick="cal()"> Calculate PCI!</button>
<br>
Total: <input id="total"> </input>
</body>
</html>
You can create a hidden div that holds the data then show that div when user clicks the button
HTML:
<div id="divToShow" style="display:none;" class="table_list" >
//put your data table here
</div>
<input type="button" name="myButton" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('divToShow').style.display = "block";
}
This should get you there: Jsfiddle.
<form id="form">
<input id="number1" type="number" min="1" name="number" placholder="add value one"> +
<input id="number2" type="number" min="1" name="number" placholder="add value one">
<button>Submit</button>
</form>
var form = document.getElementById('form');
number1 = document.getElementById('number1');
number2 = document.getElementById('number2');
form.onsubmit = function() {
var total = +number1.value + +number2.value; // add + before
alert( total );
};
function cal(){
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var recommanted;
var recommandations=[
{maxpci:1000,recommandation:'first_recommandation'},
{maxpci:2000,recommandation:'second_recommandation'},
{maxpci:3000,recommandation:'third_recommandation'},
{maxpci:6000,recommandation:'fourth_recommandation'}
];
var total=(parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
if(recommandations[recommandations.length - 1].maxpci < total ){recommanted=recommandations[recommandations.length - 1].recommandation;}
else{
for (var i = 0; i < recommandations.length; i++) {
if(total <= recommandations[i].maxpci){
recommanted=recommandations[i].recommandation;break;}
}}
document.getElementById('result').innerHTML = "Your PCI : "+total+"</br>Recommandation : "+recommanted;
}
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" type="number" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" type="number" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" type="number" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" type="number" value="" placeholder="Enter your 4th family income..."/>
<input id="members" type="number" value="" placeholder="Enter the total number of family members..."/>
</br>
<button onclick="cal()"> Calculate PCI!</button>
</br>
<div id="result">
</div>

Calculate change to be given to customer on POS javascript

Can any one help me with this, I'm trying to use this code on a POS to calculate the change to give a customer and it works for the must part.
The problem I'm having is if I an order costs £9.99 and I enter £10, instead of it calculating the change as £0.01 it calculates it as £ 0.009999999999999787
Here is the code that I'm using.
function sum() {
var og_total = document.getElementById('og_cart_total').value;
var og_tendered = document.getElementById('og_cash_tendered').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = '£';
if (!isNaN(og_change)) {
document.getElementById('og_change_given').value = og_symbol + og_change;
}
}
<input type="hidden" id="og_cart_total" value="19.99" onkeyup="sum();" />
<div class="control-group">
<label class="control-label" for="og_cash_tendered">Tendered:</label>
<div class="controls">
<input class="cm-autocomplete-off" type="text" name="payment_info[og_cash_tendered]" value="" id="og_cash_tendered" onkeyup="sum();" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="og_change_given">Change:</label>
<div class="controls">
<input type="text" name="payment_info[og_change_given]" id="og_change_given" value="£-19.99" readonly="readonly" />
</div>
</div>
there is this way but it's not as promising as it should. the best way is to use a library for long numbers if it worth the trouble.
function sum() {
var og_total = document.getElementById('txt1').value;
var og_tendered = document.getElementById('txt2').value;
var og_change = (og_tendered - og_total).toFixed(2);
var og_symbol = "£";
if (!isNaN(og_change)) {
document.getElementById('og_change_text').value = og_symbol + og_change;
}
}
<input type="text" id="txt1" value="9.99" readonly="readonly" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
<input type="text" readonly="readonly" id="og_change_text" />

Categories