Represent an idea with values
JavaScript lets a page respond to people. Start by identifying the values your feature needs. Our illustrative calculator multiplies a page count by a sample price. These sample numbers are for learning, not SiteRang’s service quotation.
const pricePerPage = 500;
const pageCount = 3;
const estimate = pricePerPage * pageCount;
console.log(estimate); // 1500const declares a variable that cannot be reassigned. Numbers support arithmetic. Strings represent text. Form inputs are usually read as strings, so convert them before doing numeric calculations.
Put a calculation in a function
A function gives a reusable operation a name. Validate input before calculating: an empty string or a negative number should not become a believable quote.
function estimatePages(rawCount) {
const count = Number(rawCount);
if (!Number.isInteger(count) || count < 1 || count > 20) {
return null;
}
return count * 500;
}The function returns null for an invalid count. Keep your validation and calculation separate from the text that you show on the page. That makes the logic easier to understand and reuse.
Connect the function to the page
An event listener responds to a form submission. preventDefault() keeps this demonstration on the same page. textContent writes plain text into the result, rather than treating user input as HTML.
const form = document.querySelector("#calculator");
const input = document.querySelector("#pages");
const result = document.querySelector("#result");
form.addEventListener("submit", (event) => {
event.preventDefault();
const amount = estimatePages(input.value);
result.textContent = amount === null
? "Enter a whole number from 1 to 20."
: `Illustrative estimate: ₹${amount}`;
});In your HTML, give the form id="calculator", the number input id="pages", and a result paragraph id="result" role="status". Add an explicit label to the input and a submit button.
Try, test, and understand the limits
Try the working example
Learning example only: ₹500 per page. This is not a service quote.
Test 1, 3, and 20 pages. Then try an empty input, a decimal, and a number outside the range. Good software handles incorrect input as carefully as correct input.
Browser-side validation helps usability, but people can alter their browser. A real paid order must calculate and validate its amount on a trusted server. Never accept a client-supplied amount as the final price or expose a private payment API key in JavaScript.
Extend it
Add an optional maintenance checkbox with a clearly labelled sample fee. Keep the total calculation in a function and update the displayed result accessibly.
Check your understanding
Keep learning
These external references are maintained by their respective publishers. SiteRang is not affiliated with them.