0

lets say we have some arbitrary amount of inputs inside #container1 and some arbitrary amount of inputs in #container2 and we want to copy the value of input with index 1 at container1 to the input with index1 at container2,then input2 to input2 and so on.

i know we can just do with jquery $("#container2 input:eq(0)").val($("#container1 input:eq(0)").val()) and the same for each one,but what if its 1000 inputs in each container?

what is the simple method to make this automatically (jquery or vanilla) ?

demo code to visualize my concept (we can modify function replicateInputValues):

function replicateInputValues(){
$("#container2 input:eq(0)").val($("#container1 input:eq(0)").val())
$("#container2 input:eq(1)").val($("#container1 input:eq(1)").val())
$("#container2 input:eq(2)").val($("#container1 input:eq(2)").val())
};

$(document).on('click', 'button', function () {
replicateInputValues();
});
button{
margin-bottom:4px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<button>COPY INPUT VALUES</button>

<div id="container1"><input placeholder="container 1"><input placeholder="container 1"><input placeholder="container 1"></div>

<div id="container2"><input placeholder="container 2"><input placeholder="container 2"><input placeholder="container 2"></div>
</body>
</html>
Vaggelis
  • 912
  • 5
  • 17

1 Answers1

0

First make a collection from both inputs. Then use .each, using the index parameter to access the corresponding input in the other collection to set the value:

const inputs1 = $('#container1 input');
const inputs2 = $('#container2 input');
function replicateInputValues() {
  inputs1.each((i, input) => {
    inputs2[i].value = input.value;
  });
};

$('button').on('click', replicateInputValues);
button {
  margin-bottom: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>COPY INPUT VALUES</button>

<div id="container1"><input placeholder="container 1"><input placeholder="container 1"><input placeholder="container 1"></div>

<div id="container2"><input placeholder="container 2"><input placeholder="container 2"><input placeholder="container 2"></div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320