JavaScript Auto-filling one field same as other

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.

You might have noticed that sometimes websites like e-commerce or some government website have two address fields in their forms.One for primary address and another for secondary address(or one for billing address and another for shipping address etc).

Most of the time people have same primary and secondary addresses and to save us from the tedious work of re-entering same data again they have some kind of option to automatically copy the contents of one fields into another.
We are going to see how to make such kind of Auto-Complete form using JavaScript.
In the form we are going to discuss, there is a checkbox and whenever it is checked, the code automatically copies values from primary address and primary zip-code to the secondary address and secondary zip-code respectively.If the checkbox is unchecked, these fields will go blank.
Here is the simple code for such kind of form:

<!DOCTYPE html> 
<html lang="en">  
<meta charset="UTF-8">      
<title>Form Auto Fill :</title>  
fieldset{ margin-bottom: 5%; }          
<h1>AutoFill Form</h1>      
//Fields for primary address  
<legend><b>Primary Address</b></legend>      
<label for ="primaryaddress">Address:</label>          
<input type = "text" name = "Address" id = "primaryaddress" required><br/>  
<label for = "primaryzip">Zip code:</label>      
<input type = "text" name = "Zip code" id = "primaryzip" pattern = "[0-9]{6}" required><br/>  
<input type="checkbox" id="same" name="same" onchange= "addressFunction()"/>              
<label for = "same">If same secondary address select this box.</label> 
// Fields for secondary address  
<legend><b>Secondary Address</b></legend>              
<label for ="secondaryaddress">Address:</label>      
<input type = "text" name = "Address" id = "secondaryaddress" required><br/>              
<label for = "secondaryzip">Zip code:</label>          
<input type = "text" name = "Zip code" id = "secondaryzip" 
                  pattern = "[0-9]{6}" required><br/>  
// Submit button in the form  
<input type = "submit" value = "Submit"/>  

// JavaScript Code 
function addressFunction() 
  if (document.getElementById('same').checked) 

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.

That’s it I hope you like it please comment your feedback.

By Rodney

I’m Rodney D Clary, a web developer. If you want to start a project and do a quick launch, I am available for freelance work.

Leave a Reply

Your email address will not be published. Required fields are marked *