HTML Element handling inside a Loop - with JS

javascript for loop
javascript loop through array of objects
for loop in html table using javascript
foreach
loop through two arrays javascript
javascript for loop array
for loop button javascript
javascript array

I have JS function to copy the name of uploaded file into text of a paragraph field.The p and input tag are inside a for loop. The logic is as follow:

// FOR LOOP start till 2 iterations
<textarea id="textfield"></textarea>
<br>
<input type="file" id="upload" name="upload" onChange="copyName">
// FOR LOOP end

JS:function to get the uploaded file name and set it in a text boxes.

 var tfield = document.getElementById("textfield");
 function copyName(input) {
  tfield.value = input.value;
 }
for (const input of document.querySelectorAll('input')) {
input.addEventListener('change', () => copyName(input));
}

Problem: The JS function works fine for one entry but if the loop count is 2 or greater the JS function does not work. Please advise how to handle dynamically value settings.

The inline handler currently isn't doing anything:

onChange="copyName">

This references the copyName variable (the function), but doesn't do anything with it. It's like doing

fn;

on a line, where fn is a function.

Call the function instead:

<input type="file" id="upload" name="upload" onChange="copyName(this)">
                                                               ^^^^^^

and then, in the handler, reference the <input>'s previous element to get to the textfield:

    function copyName(input) { 
        input.previousElementSibling.value = input.value; 
    } 

You should also consider attaching the event handler properly using Javascript instead of an inline attribute. Get a reference to the input element, then use addEventListener:

input.addEventListener('change', () => copyName(input));

Live demo:

function copyName(input) {
  input.previousElementSibling.value = input.value;
}
for (const input of document.querySelectorAll('input[type="file"]')) {
  input.addEventListener('change', () => copyName(input));
}
<input>
<input type="file">
<br>
<input>
<input type="file">

Master the art of looping in JavaScript with these incredible tricks, The For Loop is the most basic way to loop in your JavaScript code. method which helps you loop through arrays, objects, DOM elements, I hope it has taught you something new about dealing with loops in JavaScript. Finding HTML Elements by CSS Selectors. If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

You are doing two mistake.

  1. you use this onchange='copyName' instead of this onchange='copyName()'
  2. using .value instead of .innerHTML for givig input value to paragraph

<p id="textfield"></p>
<input type="file" id="upload" name="upload" onchange="copyName()"/>

<script type="text/javascript">
            function copyName() {
                var upload = document.getElementById('upload').value;
                document.getElementById('textfield').innerHTML = upload;

            } 
</script>

5 Ways To Loop Over DOM Elements With QuerySelectorAll in , There are a lot of ways to loop over a NodeList Object (List of DOM elements) that is returned by Dive Into Looping Over Elements With JavaScript In The DOM. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

Rather than inline handlers you ought to perhaps use externally registered event listeners and remove the ID attributes from any elements that are generated in a loop. Below I used PHP to simply generate a collection of file input elements of the same name and the callback prints the fakepath path into the previous textarea

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>JS: Multiple File fields</title>
        <style>
            textarea{ padding:1rem; color:red }
        </style>
    </head>
    <body>
        <form name='uploads' method='post' enctype='multipart/form-data'>
            <?php

                for( $i=1; $i <= 5; $i++ ){
                    printf('
                    <textarea cols=80 rows=3></textarea>
                    <input type="file" name="upload[]" />');
                }

            ?>
        </form>
        <script>
            const changehandler=function(e){
                this.previousElementSibling.textContent=this.value
            }
            Array.from( document.forms.uploads.querySelectorAll('input[type="file"]') ).forEach( input=>{
                input.addEventListener('change', changehandler );
            })
        </script>
    </body>
</html>

const changehandler=function(e){
	this.previousElementSibling.textContent=this.value
}
Array.from( document.forms.uploads.querySelectorAll('input[type="file"]') ).forEach( input=>{
	input.addEventListener('change', changehandler );
})
textarea{ padding:1rem; color:red }
<form name='uploads' method='post' enctype='multipart/form-data'>
	<textarea cols=80 rows=3></textarea>
	<input type="file" name="upload[]" />
	<textarea cols=80 rows=3></textarea>
	<input type="file" name="upload[]" />
</form>

Adding Click Event Listeners In A Loop In JavaScript, When you attach multiple click events to elements in a for loop, the click event gives us the Duration: 8:22 Posted: Feb 18, 2020 Using for loop and createElement() to Print out Array Content in JavaScript. Using for loop and createElement() to Print out Array Content in JavaScript. In this Article i will use a for loop to loop through all element contain inside an Array and then print out the Value line by line when the user click the ” check What is inside “ button .

Loops and iteration, In the example below, the function contains a for statement that counts the number of selected options in a scrolling list (a <select> element that� How to loop in a React component JSX Published Nov 06, 2018 If you have a set of elements you need to loop upon to generate a JSX partial, you can create a loop, and then add JSX to an array:

JavaScript for/in Statement, The for/in statement loops through the properties of an object. The block of code inside the loop will be executed once for each property. JavaScript supports� HTML markup is processed for each item in a loop. A JavaScript object literal can be passed as a parameter and can be iterated over using a property called data. If the parameter is an observable one, then any modifications made are reflected in the UI as soon as the underlying observable changes.

JavaScript continue Statement, In this example we use a for loop together with the continue statement. Loop through an array, but skip the array's element "Saab": var cars = ["BMW"� @Kloar: The question asked how to get the "next [div] element in html." The next div in the markup might not be adjacent to the element; it might be a level deeper or a level higher. – rvighne May 27 '14 at 21:54

Comments
  • Thank You , I have done the same as you advised but the file name for first input file is read correctly but on the second input element it is not working properly. It is definitely because as the page loads and 2 input objects are created but the JS is unable to get the Second input element. Please advise
  • tfield.value = input.value; It writes the value for first upload. But on the second input value it doesnt write. tfield is also generating in the For Loop
  • It works fine here, see the live snippet I edited into the answer
  • Or do you mean you want the populated textarea to be next to the input field?Your current code doesn't do that - you don't have a #textfield in the HTML you posted, so I thought your document.getElementById("textfield") was referencing a different element somewhere else. Is your actual code var tfield = document.getElementById("text");?
  • Yes, sir it exists in same document as same name