Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html forms

How to use the value of one form field in another

Charlene Grant


Allowing users to use data from another form field is a great way to make an app’s user experience quicker and easier. Let’s consider the online shopping checkout process.

As users, we sometimes use the same details in both the shipping and billing address fields during the retail checkout process. However, as e-commerce store owners, we may want to save users time by reusing the billing information.

The task

In this task, let’s consider that the user wants the billing address to be the same as the shipping address. Let’s see how to make them identical.

Customer journey flowchart
1 of 2

The solution

We can do this using an HTML form and Javascript.

The example form has a checkbox. This triggers a function that copies the values from shipping details into billing details.

To do this, follow the steps below:

1. Create the shipping and billing details input fields

Billing PostCode

<input id="billing-postcode" 
class="w3-input w3-border" 
type="text" />

We use the HTML form elements <input /> and <label /> in pairs. We reference the id given to each input in the corresponding label using the for attribute.

2. Add a checkbox

onclick="copyFunction()" />
Same As Shipping Address

The checkbox, shown in code as <input type="checkbox" />, is given an onclick attribute. This calls the function copyFunction().

3. Create the Javascript function copyFunction()

function copyFunction() {
    const pleaseCopy = document.getElementById("please-copy")
    const shippingAddress = document.getElementById("shipping-address")
    const shippingPostCode = document.getElementById("shipping-postcode")
    const billingAddress = document.getElementById("billing-address")
    const billingPostCode = document.getElementById("billing-postcode")

    if (pleaseCopy.checked === true) {
        billingAddress.value = shippingAddress.value;
        billingPostCode.value = shippingPostCode.value;
    } else {
        billingAddress.value = ""
        billingPostCode.value = ""
Defining the Javascript function

We do this in multiple steps:

  • Lines 2 to 6: We define a variable for each field using document.getElementById("field-id-goes-here").
  • Lines 8 to 14: We add an if-else statement to check the state of the checkbox.
  • Lines 9 to 10: If it returns true the vales in shippingAddress and shippingPostCode become the values of billingAddress and billingPostCode respectively.
  • Lines 12 to 13: Otherwise, the fields in billing details remain blank. The user can enter their information manually.

4. Put it all together

For this, we do the following:

  • Line 5: To connect an external Javascript file, we add a script tag in the <head> of the HTML document.
Use the value of one form field in another


html forms

View all Courses

Keep Exploring