Build a Product Total Calculator
Create an interactive ecommerce calculator with JavaScript and the DOM.
Introduction
30 Second Summary
A product page often starts with a price per item. Shoppers still need the final total after choosing their quantity and delivery.
In this project, you will build a browser-based product total calculator for an Everyday Canvas Tote. You will use JavaScript to connect the product controls to the DOM.
What You'll Build
Your finished tote product card shows an updated order total after each click of Calculate total.
By the end of this project, you'll have:
- A styled product card that opens locally in Microsoft Edge with quantity controls and delivery options.
- A JavaScript preview calculation that prints Preview total: $40 in Microsoft Edge DevTools.
- An interactive order calculator that reads browser form values. Explicit number conversion keeps totals correct. A clear message handles quantities below one.
- Secret Mission: Add a 10% bulk discount when the merchandise subtotal reaches $100. Show the saved amount directly on the product card.
Are there any prerequisites?
You need a Windows device plus basic familiarity with HTML and CSS. The project includes setup checks for Visual Studio Code and Microsoft Edge, so you can start without DOM experience.
Before We Start
This is your moment to commit to building a local ecommerce calculator. It will use the DOM to turn quantity plus delivery choices into a visible order total.
Set Up the Product Page
Your calculator needs a product page before its controls can respond to customer choices. The page gives your JavaScript a visible place to work.
A small local page removes extra platform setup. This keeps your attention on JavaScript interactions through the DOM.
You will create the project files in Visual Studio Code. You will display the finished product card in Microsoft Edge.
In this step, get ready to:
- Confirm that Visual Studio Code opens on your Windows device.
- Create the local product page files inside product-total-calculator.
- Display a styled product card in Microsoft Edge.
Confirm your editor and browser
Visual Studio Code is where you will edit the three project files. Microsoft Edge is where you will check each visible change.
- Press the Windows key to open the search bar.
- Type Visual Studio Code.
- Press Enter to open Visual Studio Code.
- Press the Windows key again.
- Type Microsoft Edge.
- Press Enter to open Microsoft Edge.
Choose the tab that matches what happened on your device.
✔️ Both apps open
Your tools are ready. Visual Studio Code can edit the files while Microsoft Edge displays the local page.
ⓧ One or both apps are unavailable
Install only the app that did not open. Both official downloads are free for this project.
- Visit the official Visual Studio Code Windows setup guide if Visual Studio Code is unavailable.
- Download the Windows User setup installer.
- Run the downloaded Visual Studio Code installer.
- Complete the installation prompts.
- Visit the official Microsoft Edge download page if Microsoft Edge is unavailable.
- Download the Windows installer for Microsoft Edge.
- Run the downloaded Microsoft Edge installer.
- Repeat the Windows search checks after the installations finish.
Installation not completing?
Confirm that you downloaded each installer from its official page. Restart the installer if Windows closed it before completion.
Ask for help with the exact stage that failed: Help me troubleshoot my Visual Studio Code or Microsoft Edge installation on Windows.
Create the project folder and files
Visual Studio Code treats an opened folder as a workspace. Keeping all three files in one workspace allows the HTML page to load its stylesheet and script by filename.
- Press the Windows key to open the search bar.
- Type Visual Studio Code.
- Press Enter to open the editor.
- Click File in the top menu.
- Select Open Folder....
- Select your Desktop in the folder dialog.
- Click New Folder.
- Enter product-total-calculator as the folder name.
The project folder now has a fixed location on your Desktop. Next, make it the active Visual Studio Code workspace.
- Select the new product-total-calculator folder.
- Click Select Folder.
You should see product-total-calculator at the top of the Explorer sidebar.
- Click New File... in the Explorer toolbar.
- Type index.html.
- Press Enter to create the file.
The new index.html file should appear beneath the folder name. It also opens in the editor.
- Click New File... in the Explorer toolbar.
- Type styles.css.
- Press Enter to create the stylesheet.
- Click New File... in the Explorer toolbar.
- Type script.js.
- Press Enter to create the script.
You should now see index.html, styles.css, and script.js in the Explorer. Leave script.js empty for this step.
Build and display the product card
The HTML defines what appears on the page. The CSS controls how those elements look.
Start with a valid page shell that links the other two files. This gives you an early browser check before you add the product content.
- Select index.html in the Explorer sidebar.
- Create the page shell by replacing the file contents with the code below:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Product Total Calculator</title>
<link href="styles.css" rel="stylesheet" />
</head>
<body>
<script src="script.js"></script>
</body>
</html>
What does this code do?
- The document metadata gives the page its title. It also configures the layout for different screen widths.
- The link element loads styles.css.
- The script element loads script.js after the page content.
- Save index.html.
- Right-click index.html in the Explorer sidebar.
- Select Reveal in File Explorer.
- Right-click index.html in File Explorer.
- Select Open with.
- Select Microsoft Edge.
You should see a blank page with Product Total Calculator in the browser tab. This proves that Microsoft Edge can open your local HTML file.
Page not opening in Microsoft Edge?
Select Choose another app under the Windows Open with menu if Microsoft Edge is missing from the first list.
Ask for focused help if Windows still opens the wrong app: Help me open my local index.html file in Microsoft Edge on Windows.
The page shell works. Add the product information and customer controls inside its body.
- Switch back to index.html in Visual Studio Code.
- Find this line: <script src="script.js"></script>.
- Insert the product card directly above that line by copying the code below:
<main class="product-card">
<p class="eyebrow">Store favorite</p>
<h1>Everyday Canvas Tote</h1>
<p class="description">
A lightweight tote for groceries, books, and daily essentials.
</p>
<p class="price">$20 each</p>
<div class="control-group">
<label for="quantity">Quantity</label>
<input id="quantity" type="number" min="1" value="2" />
</div>
<div class="control-group">
<label for="shipping">Delivery</label>
<select id="shipping">
<option value="0">Free pickup</option>
<option value="5" selected>Standard delivery ($5)</option>
</select>
</div>
<button id="calculate-button" type="button">Calculate total</button>
<p id="total" class="total">Order total will appear here.</p>
</main>
How is the product card structured?
- The product-card class groups the complete store interface inside one main element.
- The quantity input begins with a value of 2.
- The delivery menu offers free pickup or a $5 standard delivery fee.
- The element IDs give later JavaScript a precise way to find each control through CSS selectors.
- Save index.html.
- Return to the local page in Microsoft Edge.
- Click the circular refresh control beside the address bar.
You should see the Everyday Canvas Tote information with quantity controls. You should also see delivery controls plus a Calculate total button.
Product content missing?
Confirm that the entire main element sits inside the body element. It must appear above the script element.
Ask for help if the browser remains blank: Help me find why my local HTML product card is not appearing in Microsoft Edge.
The product structure is visible. Styling the page now turns the bare controls into a centered store card.
- Select styles.css in the Explorer sidebar.
- Set the page layout and card container by copying the code below into the empty file:
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
display: grid;
place-items: center;
padding: 24px;
font-family: Arial, sans-serif;
color: #1f2933;
background: #f4f7f5;
}
.product-card {
width: min(100%, 420px);
padding: 32px;
border: 1px solid #d8e2dc;
border-radius: 18px;
background: #ffffff;
box-shadow: 0 16px 40px rgba(31, 41, 51, 0.12);
}
What do these styles change?
- The universal selector keeps widths predictable when padding or borders are added.
- The body uses a grid to center the card within the browser window.
- The .product-card selector creates a white panel with spacing. It also adds rounded corners plus a soft shadow.
- Save styles.css.
- Return to Microsoft Edge.
- Click the circular refresh control beside the address bar.
You should see the product content centered inside a white card. The surrounding page should have a pale background.
Card still showing as plain text?
Confirm that styles.css is saved beside index.html. Check that the HTML link uses the same filename.
Ask for help checking the stylesheet link: Help me troubleshoot why styles.css is not changing my local index.html page.
- Switch back to styles.css.
- Style the product text by adding the code below after the existing CSS:
.eyebrow {
margin: 0 0 8px;
color: #2f855a;
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 2rem;
}
.description {
line-height: 1.6;
color: #52606d;
}
.price {
margin: 20px 0;
font-size: 1.5rem;
font-weight: 700;
}
How does the product text change?
- The eyebrow becomes a small green store label.
- The heading grows into the main focus of the card.
- The description uses softer text with extra line spacing.
- The price becomes larger and heavier.
- Save styles.css.
- Return to Microsoft Edge.
- Click the circular refresh control beside the address bar.
You should see a green Store favorite label. The product name and price should now stand out from the description.
Text styles not changing?
Check that every selector starts with the same class spelling used in index.html. Confirm that each CSS declaration ends with a semicolon.
Ask for help comparing the class names: Help me compare my HTML classes with the product text selectors in styles.css.
- Return to the bottom of styles.css.
- Style the form layout and controls by adding the code below:
.control-group {
display: grid;
gap: 8px;
margin-bottom: 16px;
}
label {
font-weight: 700;
}
input,
select,
button {
width: 100%;
min-height: 44px;
padding: 10px 12px;
border: 1px solid #9fb3c8;
border-radius: 8px;
font: inherit;
}
How do the controls line up?
- Each control group places its label above its field.
- The shared selector gives the input, menu, and button matching dimensions.
- The inherited font keeps the controls visually consistent with the card.
- Save styles.css.
- Return to Microsoft Edge.
- Click the circular refresh control beside the address bar.
You should see full-width quantity and delivery controls. Their labels should appear directly above each field.
Controls still uneven?
Confirm that the shared selector includes input, select, and button on separate lines. Keep the commas after the first two selectors.
Ask for help checking this selector group: Help me fix the shared CSS selector for my input, select, and button controls.
- Return to the bottom of styles.css.
- Finish the button and total styles by adding the code below:
button {
border: 0;
color: #ffffff;
background: #276749;
cursor: pointer;
font-weight: 700;
}
button:hover {
background: #22543d;
}
.total {
min-height: 24px;
margin: 20px 0 0;
font-size: 1.1rem;
font-weight: 700;
}
What finishes the card?
- The button gains a green background with white text.
- The hover selector darkens the button when the pointer rests over it.
- The total output receives space plus a heavier text style.
- Save styles.css.
Before you refresh, what do you expect the finished button and total area to look like?
- Return to Microsoft Edge.
- Click the circular refresh control beside the address bar.
You should see the styled Everyday Canvas Tote card. It should include quantity, delivery, and Calculate total controls.
That is your first visible project win. The browser now displays the complete static interface that your JavaScript will make interactive.
Button missing its green style?
Confirm that the button rules appear after the shared input, select, and button rules. Check that the button selector has no leading period.
Ask for help checking the final CSS blocks: Help me troubleshoot the button and total styles in my product card.
✔️ Awesome, I've got everything!
Great work. Confirm that all three files are saved and that the styled product card remains open in Microsoft Edge.
ⓧ I'd like to double check the full code
Compare your complete index.html file with this version:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Product Total Calculator</title>
<link href="styles.css" rel="stylesheet" />
</head>
<body>
<main class="product-card">
<p class="eyebrow">Store favorite</p>
<h1>Everyday Canvas Tote</h1>
<p class="description">
A lightweight tote for groceries, books, and daily essentials.
</p>
<p class="price">$20 each</p>
<div class="control-group">
<label for="quantity">Quantity</label>
<input id="quantity" type="number" min="1" value="2" />
</div>
<div class="control-group">
<label for="shipping">Delivery</label>
<select id="shipping">
<option value="0">Free pickup</option>
<option value="5" selected>Standard delivery ($5)</option>
</select>
</div>
<button id="calculate-button" type="button">Calculate total</button>
<p id="total" class="total">Order total will appear here.</p>
</main>
<script src="script.js"></script>
</body>
</html>
Compare your complete styles.css file with this version:
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
display: grid;
place-items: center;
padding: 24px;
font-family: Arial, sans-serif;
color: #1f2933;
background: #f4f7f5;
}
.product-card {
width: min(100%, 420px);
padding: 32px;
border: 1px solid #d8e2dc;
border-radius: 18px;
background: #ffffff;
box-shadow: 0 16px 40px rgba(31, 41, 51, 0.12);
}
.eyebrow {
margin: 0 0 8px;
color: #2f855a;
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 2rem;
}
.description {
line-height: 1.6;
color: #52606d;
}
.price {
margin: 20px 0;
font-size: 1.5rem;
font-weight: 700;
}
.control-group {
display: grid;
gap: 8px;
margin-bottom: 16px;
}
label {
font-weight: 700;
}
input,
select,
button {
width: 100%;
min-height: 44px;
padding: 10px 12px;
border: 1px solid #9fb3c8;
border-radius: 8px;
font: inherit;
}
button {
border: 0;
color: #ffffff;
background: #276749;
cursor: pointer;
font-weight: 700;
}
button:hover {
background: #22543d;
}
.total {
min-height: 24px;
margin: 20px 0 0;
font-size: 1.1rem;
font-weight: 700;
}
Keep script.js completely empty at the end of this step.
Your local storefront is ready for logic. Next, you will refresh your JavaScript fundamentals with a preview total in the browser Console.
Refresh JavaScript with a Preview Calculation
Your styled product card is already open in Microsoft Edge. Its price and default quantity give you familiar data for your first JavaScript result.
Before connecting those controls to the DOM, you need to prove the arithmetic works on its own. A small preview calculation keeps that refresher focused on the tote data.
In this step, get ready to:
- Store the tote price and preview quantity in constants.
- Define a function that returns the product of a price and quantity.
- Log the preview total in the browser Console.
Build the preview calculation
Constants give the product values stable names. A function accepts those values as parameters before returning the multiplication result.
- In the Explorer sidebar in Visual Studio Code, select script.js.
- Add the preview calculation by pasting the code below into the empty file:
const unitPrice = 20;
const previewQuantity = 2;
function calculatePreviewTotal(price, quantity) {
return price * quantity;
}
console.log(`Preview total: $${calculatePreviewTotal(unitPrice, previewQuantity)}`);
What does this code do?
- The unitPrice constant stores the tote price of 20.
- The previewQuantity constant stores the test quantity of 2.
- The calculatePreviewTotal(price, quantity) function multiplies its parameters. The return statement sends the result back to the calling code.
- The console.log() call runs the function. Its template literal places the returned total inside a readable message.
- Save script.js.
Verify the Console result
The Console in Microsoft Edge DevTools displays messages created by console.log(). This gives you a visible result before the calculation responds to page controls.
Before you refresh, what total do you expect from a unit price of 20 and a quantity of 2?
- Switch back to the local product page in Microsoft Edge.
- Refresh the page.
- Press Ctrl+Shift+J to open the Console tool.
You'll see Preview total: $40 in the Console. This confirms that your constants, function, return value, and arithmetic are working together.
Don't see the preview total?
- Confirm that you saved script.js before refreshing the page.
- Check that index.html still contains <script src="script.js"></script> near the bottom.
- Refresh the page again while the Console is open.
Help me find why my preview total is missing from the Microsoft Edge Console.
✔️ Awesome, I've got everything!
Great. Your saved script.js now calculates the preview total. The Console confirms the result with Preview total: $40.
ⓧ I'd like to double check the full code
Here is the complete script.js file. Make sure yours matches exactly:
const unitPrice = 20;
const previewQuantity = 2;
function calculatePreviewTotal(price, quantity) {
return price * quantity;
}
console.log(`Preview total: $${calculatePreviewTotal(unitPrice, previewQuantity)}`);
You have your first JavaScript result working in the browser. Next, you'll connect that calculation to the customer controls.
Connect the Page and Find the String Problem
Your preview calculation already proves the product arithmetic works with values written directly in script.js. The product card still cannot send its quantity or delivery choice into that calculation.
Now you'll connect the controls to your code through the DOM. The first click gives you a result you can inspect before you improve the data handling.
In this step, get ready to:
- Store references to the product controls with CSS selectors.
- Respond to the calculate button with an event listener.
- Run the first calculation to expose a string problem.
Select the product controls with the DOM
The browser needs a reference to each HTML element that your calculator reads or updates. document.querySelector() finds an element using its CSS selector.
- Switch back to script.js in Visual Studio Code.
- Scroll below the existing preview log.
- Store references to the four product elements by adding this code:
const quantityInput = document.querySelector("#quantity");
const shippingSelect = document.querySelector("#shipping");
const calculateButton = document.querySelector("#calculate-button");
const totalOutput = document.querySelector("#total");
What do these references do?
- Each document.querySelector() call finds the first element that matches its CSS selector.
- The quantityInput reference points to the quantity field.
- The shippingSelect reference points to the delivery menu.
- The calculateButton and totalOutput references connect the customer action to the visible result.
- Save script.js.
- Switch back to the local page in Microsoft Edge.
- Refresh the page.
- Confirm the Console still shows Preview total: $40 without an error.
Seeing a Console error?
Compare each selector with the matching ID in index.html. Check the quotation marks around every selector.
Help me fix the DOM references in script.js.
Respond to the calculate click
An event listener waits for a specific customer action. Your listener calls a function when the customer clicks the calculate button.
- Add the calculation function below the DOM references by pasting this code:
function calculateOrderTotal() {
const quantity = quantityInput.value;
const shippingFee = shippingSelect.value;
const subtotal = unitPrice * quantity;
const total = subtotal + shippingFee;
totalOutput.textContent = `Order total: $${total}`;
}
calculateButton.addEventListener("click", calculateOrderTotal);
What does this code do?
- The calculateOrderTotal() function reads the current quantity and delivery values.
- The subtotal calculation multiplies the unit price by the chosen quantity.
- The total calculation adds the selected delivery value.
- The textContent update places the result inside the product card.
- The addEventListener() call runs the function after a click.
- Save script.js.
- Refresh the local product page.
- Set the Quantity field to 2.
- Select Standard delivery ($5) from the Delivery menu.
Before you click, ask yourself what total two $20 totes plus $5 delivery should produce.
- Click Calculate total.
You'll see Order total: $405. Your click handler works, yet the displayed total is incorrect.
Why Does $45 Become $405?
The .value properties provide text. Multiplication with * converts the quantity text for the subtotal, so the subtotal becomes 40.
Addition with + sees the delivery value as the text 5. It joins 40 with 5 to produce 405.
Don't See the Incorrect Total?
Confirm that the quantity is 2 and the delivery option is Standard delivery ($5). Refresh the page after saving script.js.
Help me find why clicking Calculate total does not show Order total: $405.
✔️ Awesome, I've got everything!
You found the intended string problem. Your product controls now trigger the calculation from a customer click.
ⓧ I'd like to double check the full code
Your complete script.js file should match this reference:
const unitPrice = 20;
const previewQuantity = 2;
function calculatePreviewTotal(price, quantity) {
return price * quantity;
}
console.log(`Preview total: $${calculatePreviewTotal(unitPrice, previewQuantity)}`);
const quantityInput = document.querySelector("#quantity");
const shippingSelect = document.querySelector("#shipping");
const calculateButton = document.querySelector("#calculate-button");
const totalOutput = document.querySelector("#total");
function calculateOrderTotal() {
const quantity = quantityInput.value;
const shippingFee = shippingSelect.value;
const subtotal = unitPrice * quantity;
const total = subtotal + shippingFee;
totalOutput.textContent = `Order total: $${total}`;
}
calculateButton.addEventListener("click", calculateOrderTotal);
What Does This Reference Show?
This reference shows the complete state of script.js for this step. It keeps the preview calculation plus the new DOM click behavior in one file.
You have a working path from the product controls to a visible total. Next, you'll convert the form values so the same calculation produces the correct amount.
Convert Form Values and Fix the Total
Your click handler now reads the product controls through the DOM.
The local Microsoft Edge page responds whenever you click Calculate total. However, the visible $405 result exposes how JavaScript handles addition when one value is text.
Explicit conversion gives both form values a numeric type. You will use Number() while keeping the existing calculations unchanged.
In this step, get ready to:
- Convert the quantity form value into a number.
- Convert the delivery form value into a number.
- Verify both delivery choices produce numeric totals.
Convert the form values to numbers
Form controls provide text values to the click handler. Number() converts that text before the arithmetic runs.
- Switch back to script.js in Visual Studio Code.
- Find the calculateOrderTotal() function.
- Select the complete function from its declaration through its closing brace.
- Replace the selected function with the converted version below:
function calculateOrderTotal() {
const quantity = Number(quantityInput.value);
const shippingFee = Number(shippingSelect.value);
const subtotal = unitPrice * quantity;
const total = subtotal + shippingFee;
totalOutput.textContent = `Order total: $${total}`;
}
What Changed in the Function?
- The Number(quantityInput.value) expression converts the current quantity text into a number.
- The Number(shippingSelect.value) expression converts the selected delivery value into a number.
- The subtotal calculation stays unchanged.
- The total calculation now receives two numeric values.
- Save script.js.
Check Standard delivery
The same inputs that produced $405 can now reveal whether conversion fixed the addition.
- Switch back to the local Microsoft Edge page from earlier.
- Refresh the page.
- Set Quantity to 2.
- Select Standard delivery ($5) from Delivery.
Before you click, predict whether 40 and 5 will join as text or add as numbers.
- Click Calculate total.
You will see Order total: $45. That is the type mismatch fixed: the delivery fee now adds to the merchandise subtotal.
Still Seeing $405?
- Confirm that both form reads use Number() in script.js.
- Save script.js again.
- Refresh the local Microsoft Edge page again.
Help me debug the incorrect product total.
Test Free pickup
Free pickup supplies a delivery value of 0. This second path confirms the calculator handles another selected value correctly.
- Confirm that Quantity contains 2.
- Select Free pickup from Delivery.
Before you click, predict how a numeric delivery value of 0 will affect the merchandise subtotal.
- Click Calculate total.
You will see Order total: $40. Your calculator now produces correct totals for both delivery choices.
Free Pickup Total Still Wrong?
- Confirm that Free pickup remains selected.
- Confirm that Quantity contains 2.
- Refresh the local Microsoft Edge page before testing again.
Help me troubleshoot the Free pickup calculation.
✔️ Awesome, I've got everything!
Your saved script.js now converts both form values. The page shows correct totals for Standard delivery and Free pickup.
ⓧ I'd like to double check the full code
Here is the complete script.js file for comparison:
const unitPrice = 20;
const previewQuantity = 2;
function calculatePreviewTotal(price, quantity) {
return price * quantity;
}
console.log(`Preview total: $${calculatePreviewTotal(unitPrice, previewQuantity)}`);
const quantityInput = document.querySelector("#quantity");
const shippingSelect = document.querySelector("#shipping");
const calculateButton = document.querySelector("#calculate-button");
const totalOutput = document.querySelector("#total");
function calculateOrderTotal() {
const quantity = Number(quantityInput.value);
const shippingFee = Number(shippingSelect.value);
const subtotal = unitPrice * quantity;
const total = subtotal + shippingFee;
totalOutput.textContent = `Order total: $${total}`;
}
calculateButton.addEventListener("click", calculateOrderTotal);
Your calculator now treats form values as numbers. Next up, you will protect the calculation from quantities below one.
Validate the Quantity
Your calculator now converts the form values into numbers. Product totals include delivery correctly.
A mathematically correct result can still describe an impossible order. A conditional detects quantities below one before an early return stops the calculation.
In this step, get ready to:
- Add a quantity check for values below one.
- Stop invalid totals with an early return.
- Verify every quantity path.
Test the current quantity gap
The current Microsoft Edge page accepts any converted number. Testing zero reveals why arithmetic alone cannot protect the order.
Before you click, what do you expect the current calculator to show for a quantity of zero? Keep your prediction in mind.
- Switch back to the local Microsoft Edge page from earlier.
- Keep Standard delivery ($5) selected.
- Enter 0 in the Quantity field.
- Click Calculate total.
You'll see Order total: $5. The calculator has priced delivery for an impossible order.
Add the early return
The quantity check belongs before the subtotal calculation. When the value is below one, the message explains the valid range before return exits the function.
- Switch back to script.js in Visual Studio Code.
- Find the existing calculateOrderTotal() function.
- Replace that entire function with this updated version:
function calculateOrderTotal() {
const quantity = Number(quantityInput.value);
const shippingFee = Number(shippingSelect.value);
if (quantity < 1) {
totalOutput.textContent = "Enter a quantity of 1 or more.";
return;
}
const subtotal = unitPrice * quantity;
const total = subtotal + shippingFee;
totalOutput.textContent = `Order total: $${total}`;
}
How does the quantity check work?
- The if (quantity < 1) condition checks the converted quantity before the subtotal exists.
- The textContent update replaces the old total with guidance for the shopper.
- The return statement exits calculateOrderTotal() before invalid arithmetic runs.
- Valid quantities skip the conditional block. The existing arithmetic then produces the order total.
- Save script.js.
- Return to the local Microsoft Edge page from earlier.
- Refresh the page.
Before you test the new check, what should happen when the quantity is zero? Keep your prediction in mind.
- Enter 0 in the Quantity field.
- Click Calculate total.
You'll see Enter a quantity of 1 or more. The invalid order stops before a total is calculated.
Still Seeing the Five-Dollar Total?
- Check that the if (quantity < 1) block sits above the subtotal calculation.
- Check that return stays inside the conditional block.
- Confirm that script.js is saved before refreshing the page.
Help me debug my quantity validation.
✔️ Awesome, I've got everything!
Great. Double check that script.js is saved. Quantity zero should now show the validation message.
ⓧ I'd like to double check the full code
Here is the complete script.js file. Make sure yours matches exactly:
const unitPrice = 20;
const previewQuantity = 2;
function calculatePreviewTotal(price, quantity) {
return price * quantity;
}
console.log(`Preview total: $${calculatePreviewTotal(unitPrice, previewQuantity)}`);
const quantityInput = document.querySelector("#quantity");
const shippingSelect = document.querySelector("#shipping");
const calculateButton = document.querySelector("#calculate-button");
const totalOutput = document.querySelector("#total");
function calculateOrderTotal() {
const quantity = Number(quantityInput.value);
const shippingFee = Number(shippingSelect.value);
if (quantity < 1) {
totalOutput.textContent = "Enter a quantity of 1 or more.";
return;
}
const subtotal = unitPrice * quantity;
const total = subtotal + shippingFee;
totalOutput.textContent = `Order total: $${total}`;
}
calculateButton.addEventListener("click", calculateOrderTotal);
How Does the Full File Flow?
- The preview function keeps the original arithmetic example available in the Console.
- The page references connect the form controls to the calculation function.
- The click handler validates the quantity before calculating valid order totals.
Test both calculation paths
The early return only runs for quantities below one. Valid quantities continue through the same subtotal and delivery calculations that already worked.
Before the final checks, what totals should these two valid combinations produce? Keep both predictions in mind.
- Select Free pickup in the Delivery menu.
- Enter 2 in the Quantity field.
- Click Calculate total.
You'll see Order total: $40. This confirms the free-delivery path still works.
- Select Standard delivery ($5) in the Delivery menu.
- Enter 3 in the Quantity field.
- Click Calculate total.
You'll see Order total: $65. The validation protects invalid orders without changing valid totals.
Seeing the Validation Message for Three?
- Confirm that the Quantity field contains 3.
- Check that the subtotal calculation remains below the closing brace of the conditional block.
- Refresh the page after saving script.js.
Help me restore the valid calculation path.
That completes the core calculator. Quantity validation now blocks impossible orders before they reach the arithmetic.
Secret mission
Add a Bulk Discount
Your calculator can now handle valid quantities and delivery fees. Extend it with a store rule that takes 10% off merchandise worth at least $100. Show the discount beside the final total so the shopper can see what changed.
Clean Up Your Resources
Clean Up Your Resources
Your calculator runs entirely from local files. There are no ongoing costs.
Resources you used:
- Local index.html page file.
- Local styles.css styling file.
- Local script.js calculator file.
Keep everything running
This option leaves the calculator ready for more experiments. All three local files stay available.
- Keep index.html as the product page structure.
- Keep styles.css as the product card styling.
- Keep script.js as the calculator logic.
- Return to the calculator in Microsoft Edge whenever you want to test another change.
Pause - I'll come back to this later
This option closes the current workspace while preserving the files. The calculator remains ready for your next session.
- Save every open project file in Visual Studio Code.
- Close the Microsoft Edge DevTools panel.
- Close the local calculator tab in Microsoft Edge.
- Close Visual Studio Code.
Delete - I don't want to use this again
Deleting the three project files is the only destructive step here. No paid resource is affected. No external service is affected.
- Move index.html to your computer's recycle bin by using its context menu in the Visual Studio Code file sidebar.
- Move styles.css to your computer's recycle bin by using its context menu in the Visual Studio Code file sidebar.
- Move script.js to your computer's recycle bin by using its context menu in the Visual Studio Code file sidebar.
- Permanently remove only those three project files from your computer's recycle bin.
- Confirm that index.html no longer appears in the Visual Studio Code file sidebar.
- Confirm that styles.css no longer appears in the Visual Studio Code file sidebar.
- Confirm that script.js no longer appears in the Visual Studio Code file sidebar.
Nice Work!
Nice Work!
You did it! Your ecommerce product calculator now turns shopper choices into a visible order total.
You've learned how to:
- Build a styled product card with HTML. Use CSS to present it as an ecommerce interface in Microsoft Edge.
- Use the DOM to read the quantity field plus delivery menu. Register a click event that updates the order total on the page.
- Diagnose a string-to-number mismatch in JavaScript from the visible $405 result. Convert form values with Number() to produce $45. Reject quantities below one with a conditional plus early return.
- Complete the Secret Mission by adding a 10% bulk discount for merchandise subtotals of at least $100. Show the applied discount directly on the product card.
Ready to quiz yourself?