How to autofill a field in JavaScript same as another?


Following is the code to autofill a field in JavaScript same as another −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   input {
      padding: 5px;
      margin: 5px;
      display: block;
   }
   button {
      padding: 3px;
   }
</style>
</head>
<body>
<h1>Autofill a filled textbox same as another</h1>
<input type="text" class="addr" placeholder="address" />
<button class="Btn">Same as above</button>
<input type="text" class="addr" placeholder="address" />
<script>
   let BtnEle = document.querySelector(".Btn");
   let addrEle = document.querySelectorAll(".addr");
   BtnEle.addEventListener("click", () => {
      addrEle[1].value = addrEle[0].value;
   });
</script>
</body>
</html>

Output

On typing the address in first text box −

On clicking the ‘Same as above’ button −

Updated on: 16-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements