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 ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.