![]() |
![]() |
Labs
|
|---|
Having JavaScript's control structures (like "if" and "for-each" statements) at our disposal allows us to extend our order form example even further. We can now, for example, be selective about what information is included in the confirmation page, depending on values chosen on the order form. We can also check to make sure that legitimate values have been entered into the form before attempting any misleading or error-inducing calculations. Let's make some of these extensions now.
Add statements to function "submitForm" (they can be inserted directly into the code that writes the confirmation page) that will display the shirt size chosen as part of the confirmation page, but will do so only if some number of shirts was ordered.
At present, your order form should contain two such "marked" fields - one for the name, and one for the credit card number. Edit your order form now so that legitimate values must appear in these fields if an order is to be submitted. For now, we'll consider any non-blank entry in these fields as legitimate.
More specifically, add statements to function "submitForm" so that if either the name or the credit card information is left blank, an alert box is displayed with an appropriate warning message, and the function is exited (JavaScript's return statement might come in handy here).
"NaN" is JavaScript notation for "Not a Number," and is usually the result
of failing to convert a string (like blank, for example) into a number
(using ParseInt, for example). It would help our program considerably
if we could check to make sure that legitimate values had been entered
for all quantities before attempting any calculations (and well before producing a nonsensical confirmation page!).
In the context of our order form we can be a bit more specific
about what constitutes a legitimate entry for a quantity - it
must not only be a number (an integer in this case), but must
be greater than or equal to zero. Fortunately for us, JavaScript
provides a built-in function that allows us to test a number to see if it is "NaN". We can ask, for example,
Edit your order form now so that it checks to make sure that all quantity fields contain legitimate values in the above sense before attempting any calculations and, again, before even trying to produce a confirmation page.
|