Learn how to process form data

After a user has entered valid data, you can use JavaScript to process the form data. Here's how.

By Emily A. Vander Veer

Once you've verified that the user has entered valid data, it's time to do something with it. In JavaScript, that's fairly easy.

We'll calculate the total adoption fee with the following function:

function calcTotal()
  document.orderForm.totalPrice.value =
* 15.99);

Simple, eh? The calcTotal() function simply takes the number supplied by the user in the numberOrdered field and multiplies it by 15.99.

The calculated total then gets printed in the "Total sponsorship fee" box.

And, of course, here's the HTML used to call the function:

Number of brains you'd like to sponsor
<INPUT TYPE="text" NAME="numberOrdered"
  onChange="if(this.value) {
    if (!(isANumber(this.value, 'number of
brains'))) {
    } else {

This sends the number entered in numberOrdered to calcTotal() for processing, assuming it passes the isANumber() test. Notice that this JavaScript example doesn't require that the data be sent to the server for final processing. You can use similar techniques to create all kinds of online calculators, converters, or quizzes.

Note that at the beginning of our script, we define orderPlaced (a global variable) and initialize its value to "false."

var orderPlaced = false;

If the user enters a number in the "number of brains" field, we change the value of orderPlaced to "true" by adding these lines to the isANumber() function:

  if (answer == 1) {
    orderPlaced = true;

We use this variable as follows:

Total price
<INPUT TYPE="text" NAME="totalPrice" SIZE=10
  onChange="if (orderPlaced) {
    alert('Total fee is a calculated field.');

Here, if the user attempts to change the value of the totalPrice field after a valid order has been placed (orderPlaced has been set to "true"), an alert pops up informing the user she is not allowed to change that field. In addition, calcTotal() is called again to restore the value of the totalPrice field.

See it in action —>

Emily A. Vander Veer is the author of numerous Internet-related magazine articles and books, including JavaScript for Dummies, JavaScript for Dummies Quick Reference, and JavaBeans for Dummies, all published by IDG Books.

Editor's Picks

Free Newsletters, In your Inbox