Recipe 7.2. Duplicating Form Field Data


Problem

You need to give visitors to your site an easy way to enter the same information twice.

Solution

Use an onClick event handler in a form input, such as a checkbox:

 <input type="checkbox" name="billingasshipping" value="1"        onclick="BillingAsShipping(this.form);"> 

Clicking the checkbox runs a simple JavaScript that copies the values from one set of form fields to another set of form fields:

 <script language="JavaScript"> <!-- function BillingAsShipping (form) {  form.sfname.value = form.bfname.value;  form.slname.value = form.blname.value;  form.saddr.value = form.baddr.value;  form.scity.value = form.bcity.value;  form.sstate.value = form.bstate.value;  form.szip.value = form.bzip.value;  form.sctry.value = form.bctry.value;  form.semail.value = form.bemail.value; return true;  } //--> </script> 

Discussion

With a simple JavaScript function, you can give your web site visitors an easy way to copy information they have entered in one section of a form to fields in another section. E-commerce sites often offer this as an option so their customers can avoid retyping a shipping address that is the same as their billing address.

Figure 7-2 shows an example of a form that puts this feature into action.

A checkbox immediately under the "Shipping Information" heading offers customers the option of populating the shipping address fields with the same information entered under "Billing Information." The checkbox itself has no intrinsic value as far as the order form is concerned. It merely acts as a trigger for a simple JavaScript activated by the onClick event handler in the checkbox tag.

The BillingAsShipping function takes one argument: the name of the form to process. Since the form in this example does not have a value in its name attribute, the shorthand this.form works. If you assign names to your forms, you may need to tweak the code to get it to work.

In this Recipe, I've distinguished the billing fields from the shipping fields by prepending a "b" or "s" to their namessuch as blname and slname for the last names on each address on the order form.

Using a specific naming convention is not required; the function will work regardless of the field names as long as each one is unique.


When the visitor clicks the checkbox, the function replaces the values of all the shipping fields (starting with "s") with the values of analogous fields starting with "b" (the billing fields).

Figure 7-2. A checkbox can activate a JavaScript that copies information from one section of a form to another




Web Site Cookbook.
Web Site Cookbook: Solutions & Examples for Building and Administering Your Web Site (Cookbooks (OReilly))
ISBN: 0596101090
EAN: 2147483647
Year: N/A
Pages: 144
Authors: Doug Addison

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net