JavaScript Loop - Help Pls

Hello - I’m trying to copy the filename from a file input to multiple text inputs, only one text input is populated in the example below, can somebody put me right here pls to the file name is copied to all text inputs, thanks in advance:


<html>
<head>
<meta charset="utf-8">
</head>

<body>
	<form>
	<input type="file" id="fileinput"><br>
	<input type="text" id="textinput_1" class="countme"><br>
	<input type="text" id="textinput_2" class="countme"><br>
	<input type="text" id="textinput_3" class="countme"><br>
			<input type="text" id="textinput_4" class="countme">
	</form>
	<script>

const countAll = document.querySelectorAll('.countme').length; // Count elements
console.log(countAll);
for (let i = 1; i <= countAll; i++) { 
  const textinput = document.getElementById('textinput_' + i); // textinput_1, textinput_2, etc

  document.getElementById('fileinput').oninput = function() {
    textinput.value = fileinput.files[0].name;
  }
}
	</script>
</body>
</html>

as this is inside the loop, it works only for one of the textinput elements, as you are overwriting at each iteration the oninput function
consider where you actually want the loop

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.