how to close or remove a specific image in a multi uploaded images functionality Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of how to close or remove a specific image in a multi uploaded images functionality without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Here I have multi uploading image functionality.

So here if the user selects Multiple images so using the below JavaScript code we can upload multiple images.

But here I want to enhance the functionality and the uploaded images should have a cross icon like close the image if the user doesn’t want to upload the specific image he will be able to delete or remove the desired image, not all the image which image is not the good user can able to remove that image.

So please help me how can we achieve this

var loadFile = function(event) {
  for (let i = 0; i < event.target.files.length; i++) {
    var image = document.createElement('img');
    image.src = URL.createObjectURL(event.target.files[i]);
    image.id = "output";
    image.width = "200";
    document.querySelector(".cont").appendChild(image);
  }
};
<input required name="images" type="file" multiple class="form-control-file" onchange="loadFile(event)">
<p class="cont"></p>

Answer

<!DOCTYPE html>
<html>
    <body>
        <input required name="images" type="file" multiple class="form-control-file" onchange="loadFile(event)">
        <div id="cont"></div>
    <body>
    <script>
        var loadFile = function(event) {
            var imgCont = document.getElementById("cont");
            for (let i = 0; i < event.target.files.length; i++) {
                var divElm = document.createElement('div');
                divElm.id = "rowdiv" + i;
                var spanElm = document.createElement('span');
                var image = document.createElement('img');
                image.src = URL.createObjectURL(event.target.files[i]);
                image.id = "output" + i;
                image.width = "200";
                spanElm.appendChild(image);
                var deleteImg = document.createElement('p');
                deleteImg.innerHTML = "x";
                deleteImg.onclick = function() {this.parentNode.remove()};
                divElm.appendChild(spanElm);
                divElm.appendChild(deleteImg);
                imgCont.appendChild(divElm);
            }
        };

    </script>
</html>
                
We are here to answer your question about how to close or remove a specific image in a multi uploaded images functionality - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji