Occasionally, your website might offer some information that the user can customize using a form and involves a small amount of calculation. Maybe the site allows people to calculate the cost of ordering some merchandise or to compute their BMI (body-mass index). Admittedly, this is not common, but if it works for your website, it's a fine JavaScript application. This page demonstrates both of these examples.
I recently saw a form similar to the following one on a website offering customized t-shirts. The form did not allow the user to order the merchandise, but it did let them see what they were in for. This form is based on that idea.
A lot of the work is in setting up the forms, and giving an ID to
each element that we are interested in: the input
elements where we can get numbers and choices from the user and
the span
elements where we can insert output.
Both forms have an associated global variable that keeps track of the t-shirt cost ($25 for a high-quality shirt and $20 for a regular quality) and the units (centimeters and kilograms versus inches and pounds).
For the order form, whenever the user changes the value of the
quality menu, a function named qualityChange
is invoked.
That function checks the value of the menu and updates the global
variable for the t-shirt cost. Similarly, for the BMI form, whenever
the user changes the units menu, a function
named unitsChange
is invoked to deal with that.
In the order form, any time any of the three numbers is changed, a
second function, named quantityChange
, is invoked. It
gets the three numbers out of the form (the number of smalls, the
number of mediums and the number of larges) and then recalculates all
the costs and totals, inserted the appropriate ones in the document.
A simple if
statement tests to see whether the user has
ordered at least 25 t-shirts and colors the text accordingly.
The quantityChange
function is added as an event handler
to all three inputs using jQuery's .change()
method.
In the BMI form, whenever the button is clicked, a function
named calcBMI
is invoked. That function extracts the two
numbers (height and weight) from the form, converts the units to
metric if necessary, and calculates
the body mass
index. Finally, a cascaded if
statement
categorizes the BMI value and inserts the appropriate text into the
document and colors it accordingly.
Use view source
on this page to see exactly how we did it.