Sales tax and tip calculator - javascript

Hello I am trying to figure out what is wrong with my code I input $10.00 for the bill and 7 for the sales tax, and 25 for the tip. the answer should be 13.38 but for some reason i get 12.59. I am not sure where the coding went wrong?
function applyTax(){
var inputAmount = document.getElementById( 'dollars' ).value;
var salesTax = document.getElementById( 'tax' ).value;
var tip = document.getElementById( 'tip' ).value;
var totalAmount = (inputAmount*1) + (salesTax * 0.01);
var tipprcnt = (tip*0.01)*totalAmount;
var Grandtotal = ((totalAmount*1) + (tipprcnt*1)).toFixed(2);
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal;
}

It seems you're assuming you should pay tax on a tip, which wouldn't normally be the case.
If you're tipping $2.50 on a $10 bill, you'd pay $12.50. Adding a 7% tax on that would give you $13.38, which is incorrect.
What you probably want to be doing is taxing the $10, and adding a $2.50 tip to that.
Sub-Total: $10
Tax: $0.70 (7%)
Tip: $2.50 (25% of Sub-Total)
Or, in JavaScript:
var inputAmount = 10;
var tip = 0.25;
var salesTax = 0.07;
var totalAmount = inputAmount +
(inputAmount * tip) + // Add on the tip
(inputAmount * salesTax); // Add on the tax

Related

How to add a tax rate to my cost under javascript?

I'm not sure how to add tax (7%) to my cost ($6) under Javascript. Can anyone help me?
html
<div class="item main">
<h1>Enter a Title</h1>
<p>Please enter a title to calculate how much it will cost<br>
<input id = "titleBox" type = "text">
<button onclick="calculateCost()">Enter</button>
</p>
<p id= "output">Result</p>
</div>
Javascript
var titleName;
var cost = 6;
function calculateCost() {
titleName = document.getElementById("titleBox").value;
var titleLetters;
titleLetters = titleName.length;
var spaceCount = (titleName.split(" ").length - 1);
document.getElementById("output").innerHTML = "$" + (titleLetters - spaceCount) * cost;
/* "Red Car" "Red" "Car" */
}
It is pretty basic(just simple math), here is the implementation:
var titleName;
var cost = 6;
const tax = 7/100; // Added the tax
function calculateCost() {
titleName = document.getElementById("titleBox").value;
var titleLetters;
titleLetters = titleName.length;
var spaceCount = (titleName.split(" ").length - 1);
document.getElementById("output").innerHTML = "$" + ((titleLetters - spaceCount) * cost*(1+tax)); // Since we have to add tax we have to use 1+tax
/* "Red Car" "Red" "Car" */
}
Note: scroll to the right to see the upgraded fromula since it got out of the stack overflow code box

getting first time total is fine, but when changing the discount or quantity will give incorrect result

when the quantity or discount change, getting item total price is fine
(calculateItemTotal() function is defined in both input fields to capture the value and based on that giving me the item total value)
based on number of rows adding, the item total calculation is working correctly and adding the all item total and display in the total text field
first time around summation of all item total getting correct value to the total text field.
after getting total value, if I changed the quantity or discount field total text field giving me incorrect value.
html page total text field markup
<label class="control-label col-xs-5">Total: </label>
<div class="col-xs-6">
<input type="text" name="totalprice" id="finaltotalprice" class="form-control" disabled> <!-- final total value is here -->
</div>
JavaScript/jQuery function for dynamically adding rows
there in no error in executing this bit of code
// dynamically changing the row id for table rows
let rowId = 0;
$("#soid").change(function() {
$.get("../ajax/ajax_product.php?type=get_sales_order_list", {salesOrderId: $("#soid").val()} , function (data) {
if(data) {
console.log(data);
let orderItems = JSON.parse(data);
console.log(orderItems);
$("#sales_item_list").html('');
for(let list in orderItems) {
$("#sales_item_list").append("<tr>" +
"<td><input type='text' name='quantity[]' class='form-control' id='quantity_"+ rowId +"' value='"+ orderItems[list].sales_list_item_quantity +"' onchange='calculateItemTotal("+ rowId +")' ></td>"+
"<td><input type='hidden' name='unitprice[]' id='unitprice_"+ rowId +"' class='form-control' value='"+ orderItems[list].unit_price +"' readonly>"+ orderItems[list].unit_price +"</td>" +
"<td><input type='text' name='discount[]' class='form-control' id='discount_"+ rowId +"' onchange='calculateItemTotal("+ rowId +")'></td>" +
"<td><input type='text' name='itemtotalprice[]' class='form-control' id='itemtot_"+ rowId +"' ></td>" +
"</tr>");
rowId++;
}
}
});
});
calculateItemTotal() function
let finalTot = 0;
function calculateItemTotal(data) {
let quantity = parseInt($("#quantity_"+data).val()); // take the quantity value to quantity variable -- ok
if(isNaN(quantity)) quantity = 0; // make it 0 if it is not a number
let unitPrice = parseFloat($("#unitprice_"+data).val()); // take the unit price value to the unit price variable --ok
if(isNaN(unitPrice)) unitPrice = 0.00;
let tot = quantity * unitPrice; // calculation is ok
let discount = (parseFloat($("#discount_"+data).val())/100 * tot).toFixed(2); // calculation is ok
if(isNaN(discount)) discount = 0.00;
let net_total = tot - discount; // this is also ok
let with2Decimals = parseFloat(net_total).toFixed(2); // this is also ok
$("#itemtot_"+data).val(with2Decimals); // set the calculated price of product item -- ok
// this is also ok
let convertToNumber = parseFloat($("#itemtot_"+data).val());
putFinalTotal(convertToNumber); // calling for the function to set the final total, -- ok
}
function putFinalTotal(convertToNumber) {
finalTot = finalTot + convertToNumber;
console.log(typeof(finalTot));
$("#finaltotalprice").val(finalTot.toFixed(2)); // set the total value to the "total" text field
}
first time calculation
correctly adding the item totals
when ever if I changed quantity or discount, total value gives me incorrect value
ex:- I changed quantity from 10 to 100, gives me correct item total but incorrect total value
correct answer should be 14400 but gives me 15600
can please someone can give me insight, how to figure out this issue.
You need to subtract Item total price before a new sum because its current value is saved in finalTot.
Try:
let finalTot = 0;
function calculateItemTotal( data ) {
const rowTotalElement = $( '#itemtot_' + data );
const currentRowTotal = parseFloat( rowTotalElement.val() );
if ( !isNaN( currentRowTotal ) ) {
finalTot -= currentRowTotal;
}
let quantity = parseInt( $( '#quantity_' + data ).val() ); // take the quantity value to quantity variable -- ok
if ( isNaN( quantity ) ) {
quantity = 0;
} // make it 0 if it is not a number
let unitPrice = parseFloat( $( '#unitprice_' + data ).val() ); // take the unit price value to the unit price variable --ok
if ( isNaN( unitPrice ) ) {
unitPrice = 0.00;
}
let tot = quantity * unitPrice; // calculation is ok
let discount = (parseFloat( $( '#discount_' + data ).val() ) / 100 * tot).toFixed( 2 ); // calculation is ok
if ( isNaN( discount ) ) {
discount = 0.00;
}
let net_total = tot - discount; // this is also ok
let with2Decimals = parseFloat( net_total ).toFixed( 2 ); // this is also ok
rowTotalElement.val( with2Decimals ); // set the calculated price of product item -- ok
// this is also ok
let convertToNumber = parseFloat( rowTotalElement.val() );
putFinalTotal( convertToNumber ); // calling for the function to set the final total, -- ok
}

Javascript blunder

I'm attempting to create a webpage that will allow my employees to enter a number and get a number that has run through an equation. I want it to do two simple math problems as follows and output the number that's larger.
Equations
x+150=y
x*1.5+89=z
Then display the larger variable.
I can't get it to work.
I'm pretty sure it's a major noob mistake.
<script type="text/javascript">
function updateOutput() {
//get form
var form = document.getElementById("calc");
//get output
var out = form.elements["z"];
//get two numbers
var num1 = parseInt(form.elements["x"].value);
//add 150
var num2 = 150;
//multiply 1.5;
var num3 = 1.5;
//add 89
var num4 = 89;
//amount1
var amount1;
//amount2
var amount2;
//set output depending on amount
//add
amount1.value = num1+num2;
//multiple
amount2.value = num1*num3+num4;
If amount1 > amount2 Then
out.value = amount1.value
Else
out.value = amount2.value
}
</script>
Some errors:
amount1.value only works if you define amount as Object, and it doesn't need to be object here. Same for amount2.
if else notation error
Better go to some tutorial sites like w3school or codecademy or buy some books.
Changes of your code, with added form, input to demonstrate.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="calc">
<input type="number" name="x"/>
<input type="number" name="z"/>
</form>
<button onclick="updateOutput();">click</button>
<script>
function updateOutput() {
//get form
var form = document.getElementById("calc");
//get output
var out = form.elements["z"];
//get two numbers
var num1 = parseInt(form.elements["x"].value);
//add 150
var num2 = 150;
//multiply 1.5;
var num3 = 1.5;
//add 89
var num4 = 89;
//amount1
var amount1;
//amount2
var amount2;
//set output depending on amount
//add
// It's ok to just assign value to them.
amount1 = num1+num2;
//multiple
amount2 = num1*num3+num4;
// Also here, don't use amountX.value.
if (amount1 > amount2) {
out.value = amount1
} else {
out.value = amount2
}
}
</script>

Sales and tip calculator

I previously posted a code with the similar way and I am still having problems with it. this time I get 100.0712.5 when I put 10 as the bill, 7 for the sales tax and 25 for the tip. I am really new to Javascript coding and I have literally been spending hours trying to figure this out I need help.
<html>
<head>
<script type="text/javascript">
function applyTax(){
var inputAmount = document.getElementById( 'dollars' ).value;
var salesTax = document.getElementById( 'tax' ).value;
var tip = document.getElementById( 'tip' ).value;
var totalAmount = (salesTax/100) + (inputAmount);
var tipprcnt = (tip/100) * (inputAmount);
var Grandtotal = (inputAmount + (totalAmount*1) + (tipprcnt*1));
//document.getElementById( 'requestedAmount' ).innerHTML = tipprcnt;
//document.getElementById( 'requestedTax' ).innerHTML = totalAmount;
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal;
}
</script>
</head>
<body>
<h1>Sales Tax + Tip Calculator</h1>
<p>Type in your price (dollar amount). Click the "Calculate" button to receive your total.
</p>
<p>
What is the bill amount?: $<input type="text" id="dollars" /> <br>
What is the sales tax?:<input type="text" id="tax" />%<br>
how much do you want to tip?:<input type="text" id="tip" />%
<input type="button" onclick="applyTax();" value="Calculate" />
</p>
</h2>The Grand Total is:</h2>
<div id="requestedAmount"> </div>
<div id="requestedTax"> </div>
<div id="requestedGrand"> </div>
<p>Home
</body>
</html>
You were adding them as string, use parseFloat instead
http://plnkr.co/edit/6pN2Ug5qxcOSUjE5AnhJ?p=preview
function applyTax(){
var inputAmount = parseFloat(document.getElementById( 'dollars' ).value);
var salesTax = parseFloat(document.getElementById( 'tax' ).value);
var tip = parseFloat(document.getElementById( 'tip' ).value);
var taxprcnt = (salesTax/100) * (inputAmount);
var tipprcnt = (tip/100) * (inputAmount);
var Grandtotal = inputAmount + taxprcnt + tipprcnt;
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal.toFixed(2); // Round to 2 decimals
}
You should use parseFloat() to convert the inputs to numbers.
You need to multiply the input amount by the tax percentage, not add them.
You should round off the final result, because people don't want to see fractional pennies.
DEMO
When I enter $10 amount, 7% tax, 25% tip, the total is $13.20.
Use Number(input.value) by every input to convert the string values into numbers. You can use parseInt() or parseFloat instead of Number() if you want. The first converts to integer, the second converts to numbers with decimal points.
Btw forget the overusage of () and *1, it is just noise for others...
Your variable names are confusing, but I guess you wanted something like this:
var amountInput = document.getElementById("dollars");
var taxInput = document.getElementById("tax");
var tipInput = document.getElementById("tip");
var amount = Number(amountInput.value);
var taxPercent = Number(taxInput.value);
var tipPercent = Number(tipInput.value);
var grandTotal = Math.round(amount * (100 + taxPercent + tipPercent)) / 100;
var grandTotalOutput = document.getElementById("requestedGrand");
grandTotalOutput.innerHTML = grandTotal;

Jquery Calculating

I running a similar script to this script from fiddle
http://jsfiddle.net/QmTNZ/2/
I tried to modify it to work with my table.
Here is the link to the table on the product page
http://styleso1.nextmp.net/dev/shop/safari-pu-sleeve-jacket.html
I need it to calculate the Qty ( input box, Column 4) X the unit price ( Column 5 ) and show the sum in column 6
How would i modify the JS to do this?
Here is what i have for the JS
$(function(){
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td").eq(1);
console.log($qnt + " | " + $price);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find(".a-center1").text(sum);
$overall += sum;
});
$("#total").text($overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup',function(){ca();});
});
Any Help would be very appreciated
Try this
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td:eq(4)").find('.price');
console.log($qnt + " | " + $price);
var pri = $price.text();
pri = pri.replace('$', '');
var sum = parseFloat(pri) * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' + sum);
$overall += sum;
});
$("#total").text('$' +$overall);
Check Fiddle
You can save some DOM searching and text parsing by doing some simple things like adding the unit price as a data attribute to the row and retrieving it with jQuery data() method
HTML
<tr class="sum" data-unit_price="10.00">
JS
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
DEMO: http://jsfiddle.net/Jk976/3/

Categories