jQuery copy values from one set of textboxes to another

Posted written by Paul Seal on October 08, 2015 Tips

If you ever wanted a simple bit of jQuery to copy values from one set of texboxes, to another set of texboxes, this is the post for you.

This is useful for copying billing address details over to the shipping address.

I looked everywhere for a post like this to give me the answer, so now that I solved it myself, I created the post for others who are looking for the same answer.

Here is an example of it in action, press the button to copy the values over:

 

Left Side

Right Side

You can just copy and paste the code into a text file and save it as an html document:

<!DOCTYPE html>
<html>
   <head>
     <style>
        #main { width: 100%; margin: 0 auto;}
        #outer { width: 50%; height: auto; display: block; margin: 0 auto;}
        #leftside, #rightside { width: 50%; display: block; height: auto; float: left;}
        label, input { clear: left; width: 90%; display: block;}
     </style>
     <title></title>
   </head>
<body>
    <div id="main">
        <div id="outer">
            <div id="leftside">
               <p>Left Side</p>
               <input id="left1" type="text" value="Value 1" />
               <input id="left2" type="text" value="Value 2" />
               <input id="left3" type="text" value="Value 3" />
               <input id="left4" type="text" value="Value 4" />
            </div>
            <div id="rightside">
            <p>Right Side</p>
            <input id="right1" type="text" />
            <input id="right2" type="text" />
            <input id="right3" type="text" />
            <input id="right4" type="text" />
            <input type="submit" id="copyvalues" value="Copy Values" />
        </div> 
    </div>
 </div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 

 <script type="text/javascript">
    $(document).ready(function () {
       $("#copyvalues").on("click", function (e) {
          e.preventDefault();
          var leftside = $("#leftside input[type='text']");
          var rightside = $("#rightside input[type='text']");
          for (var i = 0; i < leftside.length; i++) {
             var leftValue = leftside.eq(i).val();
             var rightFieldId = $("#rightside input[type='text']")[i].id;
             $("#" + rightFieldId).val(leftValue);
          }
       });
    });
  </script>

 </body>
</html>

The script block at the bottom is where the magic is.