Thursday, January 23, 2025

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

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

Name:


City:



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


Billing Address

Name:


City:



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 above…like 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>
<br><br>
<form>
Name:
<input type=”text” name=”shippingname”>
<br>
City:
<input type=”text” name=”shippingcity”>
<br>
<input type=”checkbox” name=”billingtoo” onclick=”FillBilling(this.form)”>
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<P>
<b>Billing Address</b>
<br><br>
Name:
<input type=”text” name=”billingname”>
<br>
City:
<input type=”text” name=”billingcity”>
</form>

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.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured