Previewing multiple images with multiple file inputs

I am trying to find a way to preview multiple images uploaded from different inputs. When the button is pressed, the content from a textarea containing <img src="$img" id="img1"> is written inside a div called seeimg. The IDs for these images range from 1 to 15 (img1, img2, img3...img15), and I want the images uploaded by the user to be displayed within the seeimg div.


Here is the HTML structure:

<form method="post" enctype="multipart/form-data" id="mainform">
    Imagine 1:<br>
     <input type="file" name="img1" id="img1"><br>
         <br><br>    
    [Other input fields for images 2-14]
    Imagine 15 :<br>
    <textarea id="insert" name="content"></textarea>
    <input type="file" name="img15" id="img15"><br>
</form>
<div id="seeimg">
</div>

The current issue with the script is that it only shows the image uploaded in the first file input (

<input type="file" name="img1" id="img1">
). If another image is uploaded using this input, it changes the next image instead of the first one.
Jquery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            console.log(e.target.result+" , "+i);
            $('#seeimg #img'+i).attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("form#mainform #img"+i).change(function(){
    readURL(this);
    i++;
});

TL;DR: The script currently only works for the first file input and keeps changing other image sources when a new image is uploaded.

Fiddle: https://jsfiddle.net/eLss3ojx/6/

Answer №1

After putting in a lot of effort to understand the code, it appears that you have multiple files and are looking to display a preview for the user once the file is uploaded.

Your approach seems correct, but there are some fundamental mistakes. For example, using the same ID for both the img and input type file can cause issues. To assist in resolving these issues, I have made modifications to your code so that it displays previews of different images.

HTML

<form method="post" enctype="multipart/form-data" id="mainform">
    Image 1: <br>
     <input type="file" name="img1" id="img1"><br>
     <img id="preview-img1" />
         <br><br>     
    Image 2: <br>
     <input type="file" name="img2" id="img2"><br>
     <img id="preview-img2" />
         <br>
     ... (continued for images 3-15) ...
</form>

Javascript

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            imgId = '#preview-'+$(input).attr('id');
            $(imgId).attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}


$("form#mainform input[type='file']").change(function(){
    readURL(this);
});

Answer №2

Your JSfiddle shows that you have set the src attribute to a div instead of an image. To display the image, you need to create an image element and then append it to the div using the following code:

$('<img>').attr('id', '#pre_img' + i).attr('src', e.target.result).appendTo('#vezi');

Instead of this:

$(principdiv+'#img'+i).attr('src', e.target.result);

Furthermore, your code incorrectly binds the change handlers. It should be done in the following manner:

$("#mainform input[id^='img']").change(function() {
  readURL(this);
}); 

For more details, you can check out the JSFiddle link.

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

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

The issue of VueRouter malfunctioning in history mode within Wordpress

I have integrated Vue into my Wordpress theme, but I am facing an issue with the router when setting mode: 'history'. The site goes blank and even after trying to configure the .htaccess file, nothing seems to work. My project is located in the V ...

Adding new pages in express.js without increasing the complexity of the routes

I am currently developing a project using Express.js and have been enjoying the experience. While the site is running smoothly, I am now looking for a way to allow users to contribute by adding pages to the site through either a form with set fields or by ...

Updating div with specific class based on selected values

I have utilized Angular to display content based on selected values from a dropdown menu. Now, I am seeking a solution to dynamically add a CSS class to a div when specific values are chosen. In other words, I want to apply certain styling to the div base ...

How to transfer the application version from package.json to a different non-JSON file in Angular and node.js

While developing my Angular application, I encountered a task where I needed to extract the version number from the package.json file and transfer it to a non-json file. The content of my package.json file is as follows: { "name": "my app ...

Tips for avoiding unintended single clicks while double clicking in React

How can I make a function trigger on both single click and double click events when working with a video element in React? Currently, the single click function is also being called when double clicking. I am seeking a solution to this issue. Below is the ...

Overflowing CSS grid issue

I've been working on this for a couple of hours, but I haven't been able to get it right. I want to add labels in a grid layout with a maximum of 3 columns. If the items don't fit, they should wrap to the next row. It would be great if the i ...

What is the best way to shorten a text using ellipses based on character count, rather than line breaks

If I have a text that needs to be trimmed down to 15 characters, like "I want to trim this text into 15 characters for example," the result should be something like "I want to limit..." in my email template. Is there a way to achieve this using just CSS? ...

Modify jQuery to update the background image of a data attribute when hovering over it

Something seems to be off with this topic. I am attempting to hover over a link and change the background image of a div element. The goal is to always display a different picture based on what is set in the data-rhomboid-img attribute. <div id="img- ...

Function for asynchronous AJAX request and handling keyboard events

Looking for assistance with populating a select list based on input from a form text field using Ajax. Currently, the function partially works but there is an issue where the variable firstname = $("#fn").val(); always returns one character less than what ...

What steps should I take to address the issue of the document not being defined?

I encountered an error that I initially thought was related to node.js, but now I'm not entirely sure. How can I go about resolving this issue? [Running] node "c:\Users\Lenovo\Desktop\projectjs\index.js" c:\User ...

The React input field seems to be unresponsive to updates

I'm working on a React/Next application where users can create and update notes/jobs. However, I am facing an issue with my onChange={handleChange} function when trying to edit the input fields. Can anyone point out what might be going wrong? Thank y ...

Aligning a element at the center is not functioning properly when using margin: 0 auto;

I'm having trouble aligning elements to the center when applying margin: 0 auto. You can view the code here: https://jsfiddle.net/helloworld123/vhhx1o7n/ The goal is to align the elements in the center of the page (.entry-wrap should be centered) and ...

Is it possible to include a while loop for iteration inside a AJAX success function?

I'm currently working on dynamically creating an accordion and populating the content of each tab using AJAX. In my main HTML page, there is an empty div reserved for the accordion: <div id="accordion"></div> The desired outcome is to ha ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

Open multiple accordion sections simultaneously

In my current setup, I have a paginated loop of elements that contains an accordion. The accordion is implemented using angular-ui-bootstrap. <div data-ng-repeat="m in results"> <div class="stuff_in_the_middle"> <accordion id="a ...

The content within the flex box element is making the flex box element grow in size

I have set up a flex box container with 3 child divs inside, and I would like to maintain the same size ratio for all 3 (1:1:1). However, when I add text to the child divs, the ratios change to accommodate the overflow of text. For example: ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

Altering the dimensions of radio button options

Is it possible to change the size of a radio button using CSS in all browsers? I'm struggling to find a solution and don't want to waste my time if it's not achievable. I haven't explored CSS3 for HTML5 yet. Hmm... ...

Leverage the power of Vue Nuxt Auth to activate authentication middleware on a route-by-route

Is there a way to implement auth middleware for individual routes using Class Components? How can I achieve the same functionality as this: <script> export default { middleware: 'auth' } </script> The following method does n ...