Search code examples
javascripthtmlimageonchange

I have a list of inputs type file and it accept image only .. How can i view an image every time i add one? using onchange method


i wrote this code and its working but when i choose image it only appear in front of the first element .

<html lang="en">
<head>
    <title>Change image on select new image from file input</title>
</head>
<body>
    <ul>
        <li>
            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">
            <img class="output" width="100px" />
        </li>
        <li>
            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">
            <img class="output" width="100px" />
        </li>
        <li>
            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">
            <img class="output" width="100px" />
        </li>
    </ul>

<script type="text/javascript">
    var loadFile = function(event) {
        var output = document.getElementsByClassName('output')[0];
        output.src = URL.createObjectURL(event.target.files[0]);
    };
</script>

I just want every image to appear in front of its input.


Solution

  • you're overloading on the first <img> element every time the file changes. It's better you find the <img> next to the target input element:

    var loadFile = function(event) {
        var output = event.target.nextElementSibling;
        output.src = URL.createObjectURL(event.target.files[0]);
    };
    

    EDIT: to include for your question in the comment

    To create new input elements in JS and implement the same behavior as the other input elements, you will need to create not just the input element but the whole li node just like the structure of the existing html and append it to the ul in the DOM. Note that if the html structure changes, nextElementSibling may fail to find the corresponding img tag.

    <script type="text/javascript">
    
        var loadFile = function(event) {
            var output = event.target.nextElementSibling;
            output.src = URL.createObjectURL(event.target.files[0]);
        };
    
        const input = document.createElement('INPUT'); 
        input.type = 'file'; 
        input.accept = '.png, .jpg, .jpeg'; 
        input.onchange = loadFile;
    
        const img = document.createElement('IMG'); 
        img.width = '100';
    
        const li = document.createElement('LI'); 
        li.appendChild(input);
        li.appendChild(img);
    
        const ul = document.querySelector('ul');
        ul.appendChild(li);
    
    </script>