javascript variables and functions - javascript

I have an assignment that i need to do however I am not able to get in touch with my teacher for the next 3 days cuz of a holiday. It needs to be finished before I go back. I am NOT an expert nor anywhere near one in javascript. I am taking classes and we arent all the way finished talking about this assignment but my teacher always gives extra credit to those who can figure out a problem before we finish talking about it.
-INSTRUCTIONS-
You will need to create some variables
and functions to calculate the total cost for individual
pizza orders and calculate the Grand Total for all orders.
Use the following values for the calculations:
A large pizza costs $10
The Tax Rate is 8.25%
The delivery tip is outlined below by the customer
Use the random() method to generate the range of tip % paid by the customer, where indicated.
Format all amounts to 2 decimal places
Customer 1 orders 5 large pizza's and pays a 10% delivery tip
Customer 2 orders a random number of pizza's (between 1–25) and pays a random
delivery tip (between (0%-25%)
Simple Pizza Order!
var grandTotal = 0;
var pizzaCost = 10;
var taxRate = .0825;
var tipRate = .10;
quantity = 5;
var subTotal = pizzaCost * quantity
var tipAmount = subTotal * taxRate
var taxAmount = subTotal * taxRate
var total = subTotal + tipAmount + taxAmount
grandTotal + = total;
This is what i have so far. How do i make costumer 1's order show up on the page with the calculations and all that? I got this far but the rest is stumped me.
any help will be appreciated thanks in advance.

function Calculate() {
var pizzaCost = Number(document.getElementById('PizzaCost').value);
var tax = Number(document.getElementById('TaxRate').value);
var tip = document.getElementById('Tip').value;
tip = Number((tip.substring(0, tip.length - 1)));
var result = pizzaCost + (pizzaCost * tax) + (pizzaCost * (tip / 100));
console.log({
pizzaCost: pizzaCost,
tax: tax,
tip: tip,
total: result
});
}
function GenerateTip() {
document.getElementById('Tip').value = (Math.floor((Math.random() * 50) + 1) + "%");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div>
<h1>Simple Pizza Order</h1>
</div>
<div>
<p>Pizza Cost:
<input type="text" id="PizzaCost">
</p>
<p>Tax Rate:
<input type="text" id="TaxRate">
</p>
<p>Delivery Tip:
<input type="text" id="Tip">
<input type="button" value="Generate Tip" onClick="GenerateTip();">
</p>
<p>
<input type="button" value="Calculate" onClick="Calculate();">
</p>
<p id="result"></p>
</div>
<script>
</script>
</body>
</html>

Related

Capture Currency in Span Class, Divide by 12 Round up and Display

I'm not very good at this and have tried last few days searching up and down for any kind of answer to help solve my problem. I've only pieced together the below. I would like to grab the generated span class value, / by 12, round up to the nearest penny and than display elsewhere on the same webpage. Any help would be greatly appreciated and thank you in advance.
const price = document.getElementsByClassName('price-value')[0].innerHTML; // Price of item before tax
// Calculate total after tax to two decimal places
let totalPrice = price / 12;
totalPrice.toFixed(2);
document.getElementById("demo").innerHTML =totalPrice
<span class="price-value model-price-value-sale">
$1,349.95
</span>
<p id="demo"></p>
First you need to convert the price from currency to an actual number by:
Number(price.replace(/[^0-9\.-]+/g,""))
Then use the Math.ceil() function to round up.
So it will be like that:
const price = document.getElementsByClassName('price-value')[0].innerHTML; // Price of item before tax
// Calculate total after tax to two decimal places
//let totalPrice = Math.ceil(Number(price.replace(/[^0-9\.-]+/g,"")) / 12);
let totalPrice = Math.round((Number(price.replace(/[^0-9\.-]+/g,"")) / 12)* 100)/100;
document.getElementById("demo").innerHTML =totalPrice
<span class="price-value model-price-value-sale">
$1,349.95
</span>
<p id="demo"></p>

I cannot find why this simple JS isn't working. (Sales Tax Calculator)

My HTML is a simple entry form like this:
<div id="taxCalc">
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" >
<span id="subtotal_message">Enter order subtotal</span><br />
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" >
<span id="tax_rate_message">Enter sales tax rate (99.9)</span><br />
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br />
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br />
<label> </label>
<input type="button" id="calculate" value="Calculate" onclick="calculate_click()">
<input type="button" id="clear" value="Clear" onclick="clear_click()">
And my JS is 2 simple functions...
var subtotal, taxRate, salesTax, total;
function setValues() {
subtotal = document.getElementById("subtotal").value;
taxRate = document.getElementById("tax_rate").value;
salesTax = document.getElementById("sales_tax").value;
total = document.getElementById("total").value;
}
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
I have included a JS Fiddle link for more information as well: http://jsfiddle.net/tjhillard/nkHxe/1/
I want the sales tax and the total to display inside the appropriate fields when the "Calculate" button is clicked.
Thank you in advance for your help!
you just need to update the values back:
change this:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
}
into:
function calculate_click() {
setValues();
salesTax = (subtotal * taxRate) / 100;
total = subtotal + salesTax;
// place the value in the form
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
updated version of your code: http://jsfiddle.net/nkHxe/4/
It should be in the following way:
function calculate_click() {
setValues();
salesTax = subtotal * taxRate / 100;
total = subtotal + salesTax;
document.getElementById("sales_tax").value = salesTax;
document.getElementById("total").value = total;
}
http://jsfiddle.net/nkHxe/5/
P.S
Keep in mind that your code is bad-organized ))
1) You don't write back the values. Maxim and Balexandre already showed how.
2) total is a concatenation of a string with a number which leads to a string again. This has not been solved by Maxim and Balexandre.
By directly reading from the input field, you get strings back. So, parse them first into numbers. Example:
parseInt(document.getElementById("subtotal").value)
In your code, you have the issue when calculating total as explained above. The issue does not occur for salesTax because the strings are automatically converted thanks to the math operations you apply.
Hope this helps.
Updated, Fully Working, total code Fixed where Integers were Passed (Concatenated) as Strings.
Code added,
subtotal = parseInt(document.getElementById("subtotal").value)
total = parseInt(document.getElementById("total").value)
Link,
http://jsfiddle.net/nkHxe/150/
Thanks to TJH, Balexandre, Maxim and Patrick :)

Working on a code but the calculations do not work

So I am working on this code and I cannot seem to be able to combine the radio button amounts with the inputted amount in the textbox. The submit button is supposed to calculate. Here is the question, I am suppose be creating this code for.
Many companies normally charge a shipping and handling fee for purchases. Create a Web page that allows a user to enter a purchase price into a text box;
Include a JavaScript function that calculates shipping and handling.
Add functionality to the script that adds a minimum shipping and handling fee of $1.50 for any purchase that is less than or equal to $25.00.
For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling fee.
The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling fee of $5.00.
After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box
This is the code I have so far. Any tips would be helpful. I can not figure out what I am doing wrong or how to fix it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Calculate Shipping</title>
<script type="text/javascript">
/* <[CDATA[ */
var price=[];
var shipping=[];
var total=price+shipping;
function calculateshipping(){
var price = parseFloat(document.getElementByid('ent').value);
var total = (price <=25) ? price +1.50 : 1.1 * price;
window.alert("the purchase price with shipping is $" + total.tofixed(2));
}
function calculateShipping(){
if (price <=25){
shipping = (price =1.25);
}
else{
shipping = (price *10/100);
}
window.alert("The purchase price with shipping is "
+document.calculate.ent.value);
}
/*]]*/
</script>
</head>
<body>
<form name ="calculate" action="">
<p>
Enter Purchase Price
</p>
<input type="text" name="ent" />
<input type="button" name="button" value="submit" Onclick="calculateShipping()"/>
</form>
</body>
</html>
First, change your input tag like the comment on your post mentioned:
<input type="text" name="ent" id="ent" />
Then replace your entire script tag with this:
<script type="text/javascript">
function calculateShipping(){
price = parseFloat(document.getElementById("ent").value);
if (price <=25){
shipping = 1.5;
}else{
shipping = (price *10/100);
}
total = price + shipping;
window.alert("The purchase price with shipping is "+total);
}
</script>
Adding the 'id' attribute gave something for javascript to grab onto when executing the function. Each time you click, it gets the value of that input element and parses it as a float.
Well first off you have two javascript methods named CalculateShipping() - how do you determine what is getting executed? Shouldn't it be just one single method CalculateShipping() like this
function calculateshipping(){
var price = parseFloat(document.getElementByid('ent').value);
var total = (price <=25) ? price +1.50 : 1.1 * price;
window.alert("the purchase price with shipping is $" + total.tofixed(2));
if (price <=25){
shipping = (price =1.25);
}
else{
shipping = (price *10/100);
}
window.alert("The purchase price with shipping is " + document.calculate.ent.value);
}
Seems like quite a basic problem, change shipping = (price =1.25); to just shipping = 1.5;. Then just calculate the price and alert it:
if(price <= 25)
shipping = 1.5;
else
shipping = (price*10)/100;
price += shipping;
alert(price);
Here is a fiddle: http://jsfiddle.net/HMRNB/

Why can't I set my input field with MooTools?

Ive got a document and when the user enters something into one input I need to show a response in a second input box. I can get the user given value, i can process it, but when I try to set the second input box with the result I get the error $.field is null. Here is the code:
$('places').addEvent('keyup', function(){
var places = $('places').value;
alert("PLACE: "+places);
var price = values[places];
var nights = $('nights').value.toInt();
alert("NIGHTS: "+nights);
var total = price * nights;
alert("TOTAL: "+total);
$('pricepernight').set('text', total);
$('pricetotal').set('text', total - ((total / 100) * 21));
});
So I get the place value. I pull the price of the place out of an assoc array. I then multiple that price by the amount of nights field in by the user and this is then my total amount. It is this amount that I cannot set to. Note that the alert shows the correct amount.
and the html looks like this
<div class='block'>
<input type="text" id="places" />
</div>
<div class='block'>
<label for="nachten">Aantal nachten</label>
<input type="text" id="nights" />
</div>
<div class='block long'>
<span class='label'>Prijs per slaapplaats per nacht</span>
<input type="text" class='resultfield' id='pricepernight' />
</div>
<div class='block last'>
<span class='label'>Totaalprijs excl. btw</span>
<input type="text" class='resultfield' id='pricetotal'/>
</div>
Firebug responds:
String contains an invalid character
[Break On This Error]
...x:\'4W\',3X:18.1l,al:18.1l,1Q:18.1l,as:18.1l,8S:18.1l,1F:O,3E:{x:\'1u\',y:\'1o\'...
Any ideas/suggestions anyone? Thank you in advance!
right. you seem to have used a mix of mootools and jquery code.
$('nights').addEvent('keyup', function(){
var places = $('places').value;
var price = values[places];
var nights = $('nights').value;
var total = price * nights;
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
in mootools 1.2+, this should be:
$('nights').addEvent('keyup', function(){
var places = $('places').get('value');
var price = values[places];
var nights = $('nights').get('value');
var total = price * nights;
alert(total);
$('pricepernight').set('value', total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
there's an implied global array values. also, this is not very safe as nights may not be integer.
the point is. #id -> id and .val() -> set('value', 'newvalue') - or .get('value')
There are couple of minor mistakes here.
First, you should use # sign to select based on your id attributes
like places and nights
Check http://api.jquery.com/id-selector/
Second, use val() to read the value from the html controls rather
than value
Check http://api.jquery.com/val/
try this
$('#nights').keyup(function(){
var places = $('#places').val();
var price = values[places];
var nights = $('#nights').val();
var total = parseInt(price) * parseInt(nights);
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
and what is values[places]?

Create a submit button which will calculate a shipping and handling

I need this code to calculate the sales tax when you hit the submit button and I can't get it to work. I need to figure out how to connect it to the function. Can someone please point out where I am going wrong? I am very new at this and am wondering what I am doing wrong with my code. This is homework, I am not looking for the answer I just need someone to direct me in the right way.Thanx
My assignment is:
Many companies normally charge a shipping and handling fee for
purchases. Create a Web page that allows a user to enter a purchase
price into a text box; include a JavaScript function that calculates
shipping and handling. Add functionality to the script that adds a
minimum shipping and handling fee of $1.50 for any purchase that is
less than or equal to $25.00. For any orders over $25.00, add 10% to
the total purchase price for shipping and handling, but do not include
the $1.50 minimum shipping and handling fee. Th e formula for calculating
a percentage is price * percent / 100. For example, the formula
for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which
results in a shipping and handling fee of $5.00. After you determine
the total cost of the order (purchase plus shipping and handling),
display it in an alert dialog box.
Here is my Code: I need this code to calculate the sales tax when you hit the submit button and I can't get it to work. Can someone please point out where I am going wrong?
Code:
<script type="text/javascript">
/*<![CDATA [*/
//Shipping & handling fee
var price=[];
var shipping=calculateShipping(price);
var total=price+shipping;
function calculateShipping()
{
var num = new Number(price);
//This will add $1.50 to any purchases that are less than or equal to $25.00.
if (num <= 25){
return 1.5;
//Here 10% will be added to any purchase that is greater than $25.00 but do not inlcude the
$1.50 fee.
} else{
return num * 10 / 100;
}
}
window.alert("Your total is $" + total + ".")
/* ]]> */
</script>
</head>
<body>
<h1>Enter Purchase Price Here</h1>
<script type="text/javascript">
/* <![CDATA[ */
document.write(parseFloat");
if(price <=25.00){var shipping=1.50}
else{var shipping=price*(10/100)};
var total=(price+shipping).toFixed(2);
/* ]]> */
</script>
<form id="btncalcprice" action="submit-form.php">
<input type='text' name='query'>
</form>
<form>
<input type="button" value="Submit" onClick="alert('YOUR total is $'); return true">
</form>
</body>
EDIT: Reviewed Code
You have some syntax issues in your code, additionally the methodology you were following was not quite correct. You need to call the function from the button onclick event, then run your JavaScript. You will find what you need in the updated code example below. Make note that I used parseFloat instead of parseInt in order to incorporate decimals...
<script type="text/javascript">
/*<![CDATA [*/
function calculateShipping() {
var price = document.getElementById('price').value;
//This will add $1.50 to any purchases that are less than or equal to $25.00.
if (price <= 25){
price=parseFloat(price) + 1.5;
} else {
//add 10%
var percentToAdd=parseFloat(price) * .1;
price=parseFloat(price)+parseFloat(percentToAdd);
}
document.getElementById('result').innerHTML='Total shipping cost: '+price;
}
/* ]]> */
</script>
</head>
<body>
<h1>Enter Purchase Price Here</h1>
<div id="result"></div>
<input type="text" name="price" id="price">
<input type="button" value="Submit" onClick="calculateShipping(); return false;">
</body>
First of all you dont need the form action if you are just calling a function, secondly if you want to prevent the default submit of the form, then return false in your onclick... it should look like this:
onclick="calculateShipping(); return false;"

Categories