Forms sometimes ask for the same information twice, such as office and residence addresses. A “Same as above” control can copy the first group into the second so the user does not retype identical values.
residenceAddress1.value = officeAddress1.value;
residenceCity.value = officeCity.value;
function copyAddress() {
residenceAddress1.value = officeAddress1.value;
residenceAddress2.value = officeAddress2.value;
residenceCity.value = officeCity.value;
residenceState.value = officeState.value;
}
The original example uses two radio buttons. That pattern is preserved, but event listeners keep JavaScript out of the HTML attributes.
<label><input type="radio" name="copy" value="yes"> Same as above</label>
<label><input type="radio" name="copy" value="no"> Not same</label>
document.querySelectorAll('input[name="copy"]').forEach((radio) => {
radio.addEventListener("change", () => {
if (radio.value === "yes") {
copyAddress();
} else {
clearResidence();
}
});
});
function clearResidence() {
[residenceAddress1, residenceAddress2, residenceCity, residenceState]
.forEach((field) => { field.value = ""; });
}
This example copies a snapshot when “Same as above” is selected. If the office address changes later, the residence address does not automatically change unless you also listen for input events. For most forms, a one-time copy is less surprising because it does not overwrite later edits.
If one field is a dropdown, assigning the destination select’s value selects the matching option. See copy form data with a listbox.
Radio button click events · Event handling · Select and copy textarea text
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| shankar | 03-12-2014 |
| The above radio button example is very helpful to understand the onclick event to copy the field values and How, if a table contains radio button and column names in a html form on while loop when a radio button and update command button clicked the second html form should reflect the corresponding fields in the form1. | |
| sarojini rout | 08-01-2015 |
| Thank you so much. | |