How To Use JavaScript To Copy Text From One Field To Another

By Scott Clark

Often when creating a form on a web page, you need your customers to fill out a field such as a mailing address, as well as a billing address. Instead of having your customers fill out the form twice, you can use JavaScript to copy the form's data from one field to another.

Show Me The JavaScript

The JavaScript itself is used to grab the data that has been entered into one form field, and when the checkbox is selected (checked), it copies that data to another field in the form. The form looks like this:

Mailing Address

Check this box if Billing Address and Mailing Address are the same.

Billing Address


The JavaScript used to achieve the effect looks like this:

function FillBilling(f) {
  if(f.billingtoo.checked == true) {
    f.billingname.value = f.shippingname.value;
    f.billingcity.value = f.shippingcity.value;
To add more fields, just add to the parameters shown this:
    f.billingstate.value = f.shippingstate.value;
    f.billingzip.value = f.shippingzip.value;
The HTML for the form you will use looks like this:
<b>Mailing Address</b>
<input type="text" name="shippingname">
<input type="text" name="shippingcity">
<input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<b>Billing Address</b>
<input type="text" name="billingname">
<input type="text" name="billingcity">
Simple and quick! No need for your site's customers to have to fill out a form twice--it's irritating and just not necessary!

CSS can be used to enhance the appearance of the form. You can find out more about that in our tutorial called HTML Forms: From Basics to Style: Layouts.

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.