Tips for implementing a loop within the file input change event

Hello everyone, I need assistance with the code below.


function fileValidation() {
  var fileInput = document.getElementById('filech');
  var filePath = fileInput.value;
  var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
  if (!allowedExtensions.exec(filePath)) {
    alert('error .jpeg/.jpg/.png/.gif ');
    fileInput.value = '';
    return false;
  } else {
    //Image preview
    if (fileInput.files && fileInput.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById('imagePreview').innerHTML = '<img src="' + e.target.result + '"/>';
      };
      reader.readAsDataURL(fileInput.files[0]);
    }
  }
}

To upload multiple photos:

<input id="filech" type="file" name="file_img[]" multiple onchange="return fileValidation()" />

Then display the images in the section below:

<div id="imagePreview"></div>

I would like to display all uploaded pictures at once instead of one by one. Can someone guide me on how to use a loop for this? Thank you in advance!

Answer №1

To accomplish this task using a loop, you can implement a for loop as shown below:

    for (var i = 0; i < fileInput.files.length; i++) {
      if (fileInput.files && fileInput.files[i]) {
        var reader = new FileReader();
        reader.onload = function(e) {
          document.getElementById('imagePreview').innerHTML += '<img src="' + e.target.result + '"/>';
        };
        reader.readAsDataURL(fileInput.files[i]);
      }
    }

Note:

It's important to note the change made to

document.getElementById('imagePreview').innerHTML +=
, ensuring that all iterated images are displayed in the preview section instead of replacing each other.

An alternative approach would be to create an img element for each image during iteration and append it to the preview div like so:

for (var i = 0; i < fileInput.files.length; i++) {
  if (fileInput.files && fileInput.files[i]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var img = document.createElement("img");
      img.src = e.target.result;
      document.getElementById('imagePreview').appendChild(img);
    };
    reader.readAsDataURL(fileInput.files[i]);
  }
}

Demo:

function fileValidation() {
  var fileInput = document.getElementById('filech');
  var filePath = fileInput.value;
  var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
  if (!allowedExtensions.exec(filePath)) {
    alert('error .jpeg/.jpg/.png/.gif ');
    fileInput.value = '';
    return false;
  } else {
    //Image preview
    for (var i = 0; i < fileInput.files.length; i++) {
      if (fileInput.files && fileInput.files[i]) {
        var reader = new FileReader();
        reader.onload = function(e) {
          var img = document.createElement("img");
          img.src = e.target.result;
          document.getElementById('imagePreview').appendChild(img);
        };
        reader.readAsDataURL(fileInput.files[i]);
      }
    }
  }
}
<input id="filech" type="file" name="file_img[]" multiple onchange="return fileValidation()" />


<div id="imagePreview"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to efficiently handle conditional rendering in React when passing data from Children to Parent

Just starting out with React, currently exploring react 16.13 and looking into how to achieve the following: Sending data from Child Components to Parent Components If the passed data is "true", display the specific Child component on the Parent page. We ...

AngularJS meta tags featuring dynamic asynchronous content

I am currently facing a challenge with my angular application that is running within a .net application. My main goal is to implement meta tags for SEO and other purposes. However, the issue I'm encountering is that I cannot determine the page title u ...

Sending a object as an argument to a function

Could someone please help me understand the purpose of passing an object as a function parameter? I have been trying to learn Next.js and they frequently use this method in their code. If anyone could provide a brief explanation of why this is done, it wo ...

Gather a linear array of deeply nested information

Below is a dictionary: var objectSchemasList = { 1: [ { name: 'list_field1_1', uuid: 'uuid1', fieldObjectSchemaId: 2 }, { name: 'list_field1_2', uuid: 'uuid2', f ...

Obtain the value from the controller of the amazing-rating component

Currently utilizing the amazing Rating AngularJS library available at https://github.com/bandraszyk/awesome-rating I am interested in understanding how to retrieve the selected value and store it in my controller. The $scope.rating is returning undefined ...

Creating a mesmerizing parallax effect for your image: A step-by-step guide

Looking for help to create a parallax effect on an image when hovered over. Does anyone have any advice or resources? Feeling frustrated at the moment. Here is an example link for reference: http://codecanyon.net/item/jquery-moving-perspective/full_scre ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

Add the file to the array field

I struggle with manipulating sub documents in MongoDB, especially when trying to implement an address book structure like the one below: { [<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e5e3f5e2a1d0fdf1f9fcbef3fffd"> ...

Once the ajax request is finished, load only the <script> tags that have specific ids

I'm currently implementing infinite-scroll to dynamically load more content which includes <script> tags that need to be executed. To achieve this, I have created the following code as an ajax-callback: JS on load ajax callback: function a ...

The calculation of Value Added Tax does not involve the use of jQuery

My form setup is as follows: <form method="post" action="" id="form-show"> <table class="table table-bordered table-striped table-hover" id='total' style="width:100%;"> ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Checking password fields in Angular upon submission or when they have been edited

i created a controller and form with validation rules, but i'm struggling to ensure that the confirm_password matches the password? html <div class="col-md-5" ng-controller="RegisterController as vm"> <form id="sign_up" name="SignUp" ng ...

The protocol at msa port 587 is unidentified with SSL23_GET_SERVER_HELLO

For sending email notifications when a new user registers or forgets their password, I am currently working on a Linux environment with an app built using node.js. Error: [Error: 140020013401920:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown ...

Creating a vendor bundle in create-react-appReady to optimize your create-react

When using the create-react-app tool, how can you specifically create a separate vendor bundle? While code splitting can be achieved easily with the react-code-splitting package, I have not been able to find clear instructions on generating vendor bundles ...

JavaScript - Deleting the last element of an array

I have currently integrated a third-party API to visualize data using Highcharts. This external API provides data specific to the current month, such as March, April, May, and so on. graphArrOne contains an array with 251 elements. graphArrTwo contains ...

What is the best way to submit form data along with an image using Angular?

Recently, I built an application where users can submit form data along with an uploaded image. Since I am new to Angular, I am facing some challenges in merging the user-submitted data model and the image upload using the FormData method. Can anyone guide ...

Access the JavaScript array within a click function by dynamically generating the array name

Here's a scenario where I have an array like this: var first_array = ['foo','bar','foobar']; My goal is to run a click function that retrieves the array's name and iterates through its elements. The array has an ID ...

Scripts fail to load randomly due to RequireJs

I have obtained an HTML template from a platform like Themeforest, which came with numerous jQuery plugins and a main.js file where all these plugins are initialized and configured for the template. I am now in the process of developing an AngularJS applic ...

Problem encountered with Blueimp gallery and Twitter Bootstrap

Blueimp gallery is being used to showcase a set of 8 images on a website, divided into two rows. The 5th thumbnail (first image on the second row) appears broken, even though it can be seen in the carousel presentation. Here's the link to view the th ...

What is the Most Effective Way to Arrange an Array of Objects Based on Property or Method?

Looking for ways to enhance my array sorting function, which currently sorts by property or method value. The existing code is functional, but I believe there's room for improvement due to redundant sections. optimizeSort(array: any, field: string): ...