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

Node.js server for Cross-Origin Resource Sharing

I'm brand new to Node.js and I'm trying to run some example code, but I keep encountering CORS issues. Server.js var http = require('http'); var io = require('socket.io'); server = http.createServer(function(req, r ...

Combining multiple PNG images onto a base image in PHP

I need assistance in merging 24 images with single dashes highlighted into a base circle image using PHP GD, JS or CSS. All images are in PNG format. Your help would be greatly appreciated. ...

Create a PHP form that includes a dropdown menu for selecting the quantity, allowing users to insert multiple rows of data inputted into the form

My first time posting something here. The issue I'm facing is: I have an HTML form with various variables. A dropdown for Quantity that should insert the data into a MySQL table multiple times based on the chosen quantity. For example, if the dropd ...

"Learn the process of customizing the border color of a drop-down menu using

Is there a way to add validation to a drop-down menu so that the border color turns red if an option is not selected? $("#MainContent_ddlSuppliers option:selected'").css("border", "1px solid #F78181"); ...

"How to ensure a background image fits perfectly on the screen in IE10

I am facing a problem while trying to set the background image in CSS to fit the screen. It works fine with the latest version of Chrome, but there is an issue with IE 10. html { border-top: 10px solid #8A85A5; background: url("http://www.lifeintempe.com/ ...

What is the best way to transform arrays like this into a JSON object?

Below is an array that I need to convert into an object: [ [ '560134275538747403', 39953 ], [ '411510958020624384', 36164 ], [ '468512396948930576', 31762 ], [ '482286641982078977', 29434 ], ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Navigating in CodeIgniter

I am facing a challenge with redirecting to another page in codeigniter, below is my JavaScript code snippet: <script type="text/javascript> $(document).ready(function () { var url = $('#baseurl').val(); var form = $(& ...

Troubleshooting CSS Navigation Drop Issue Specific to Google Chrome. Seeking Feedback on Rails Tutorial Experience

I'm currently working my way through the amazing Rails Tutorial and have encountered a problem with the Navigation bar dropping down into the body of the page, but this issue only seems to occur in Chrome (I'm using Linux, Ubuntu 10.10). I'v ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

The directory for foundation images cannot be found

Currently, I am in the process of learning Foundation framework and I have encountered some issues with my code. My goal is to display images for different devices such as mobile, tablet, and desktop. However, despite double-checking the path to the images ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

An error occurred while trying to access the stored data at https://localhost:5000. The SSL protocol encountered

I am attempting to utilize an API to retrieve data and transfer it to MongoDB from my React application to the Node.js server, but I keep encountering an error message along with another issue in the console. https://i.stack.imgur.com/Bj4M6.png Despite e ...

Make the text area occupy the full width of the remaining screen space

I've been struggling to make the text area fill the remaining width of the screen. Everything is set up nicely, but I just can't seem to find a solution to get it to expand and occupy the rest of the available space. I intentionally refrained fr ...

Unexpected element layout issues

Attempting to create a basic website that utilizes the flickr api, retrieves photos and details, and displays them using bootstrap. However, there seems to be an issue that I am unsure how to resolve. Currently, my code is functioning like so: https://i.s ...

Store additional data with the visitor ID WEB in Fingerprint JS V3

After browsing through similar questions, I couldn't find a solution that fits my needs. Basically, I have a website where a random emoji is generated and stored in local storage. However, this method is not effective as users can easily delete their ...

Visit a webpage on my site

Is it feasible to embed a website within another website? Suppose I have my index.html file. What if in the center of that file, we include an iFrame or similar element that loads , allowing users to explore Google directly on my website? ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

I have been struggling to get AJAX to work properly with Load and selector, but no matter what I try, the scripts just won

Yesterday, with the assistance provided here, I discovered how to load AJAX'ed content and maintain the page structure. However, I encountered an issue where the script tags were not loading. Upon further investigation, it appears that when using a se ...