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.
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.
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:
<label
for="billing-postcode"
class="w3-text-deep-purple">
Billing PostCode
</label>
<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.
<input
id="please-copy"
type="checkbox"
class="w3-check"
onclick="copyFunction()" />
<label
for="please-copy"
class="w3-margin">
Same As Shipping Address
</label>
The checkbox, shown in code as <input type="checkbox" />
, is given an onclick
attribute. This calls the function copyFunction()
.
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 = "" } }
We do this in multiple steps:
document.getElementById("field-id-goes-here")
.if-else
statement to check the state of the checkbox.true
the vales in shippingAddress
and shippingPostCode
become the values of billingAddress
and billingPostCode
respectively.For this, we do the following:
<head>
of the HTML document.RELATED TAGS
CONTRIBUTOR
View all Courses