Reputation: 21
Here is the question: 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. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
I am beginner at JavaScript and struggling to get my code to work. It does display an alert box with the value entered by the user but doesn't add anything. Although, I don't know why the formula doesn't work. Please help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//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>Calculating Shipping & Handling</title>
<script type="text/javascript">
/* <![CDATA[ */
var price=[];
var shipping=[];
var total=price+shipping;
function calculateShipping(){
if (price <= 25){
shipping = (price + 1.5);
}
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>
Upvotes: 1
Views: 3616
Reputation: 46
Try:
function calculateShipping() {
var price = parseFloat(document.getElementById('ent').value);
var total = (price <=25) ? price + 1.5 : 1.1 * price;
window.alert("The purchase price with shipping is $" + total.toFixed(2));
}
You should also add some validation to your input, because if a non-numeric value is entered, it will crash your function.
Upvotes: 2
Reputation: 4075
This is obviously homework, so I will put you on the right track.
There are a couple problems with the code:
var total=price+shipping;
happens before you actually calculate the shippingdocument.calculate.ent.value
you actually want to display the value of total
.price
variable. You might consider simply passing the price as an argument to the calculateShipping()
function so it would be function calculateShipping(price) { ... }
Upvotes: 3