Tips for showcasing several thumbnails simultaneously as you upload images on a webpage with HTML and JavaScript

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

    reader.onload = function(e) {
      $('#selectedImage')
        .attr('src', e.target.result)

    };

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

<head></head>

<body>
  <ul>
    <li>
      <input type='file' onchange="displayImage(this);" />
      <img id="firstImage" src="#" alt="first image" />
    </li>

    <li>
      <input type='file' onchange="displayImage(this);" />
      <img id="secondImage" src="#" alt="second image" />
    </li>
  </ul>
</body>

</html>

> Blockquote

"If you click on any 'choose image' button, the image will be displayed in the first case only. I tried changing the IDs in both cases and in the JavaScript as well but it didn't work. The code above provides a solution on how to display an image in HTML."

Answer №1

The issue lies in the requirement for IDs to be unique. To solve this problem, I introduced a new attribute called document-up, which successfully resolved the issue at hand. In situations like this, it is viable to utilize attributes or classes to select multiple elements.

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

    reader.onload = function(e) {
      if (option == 1){
         $("#documentUpload1")
         .attr('src', e.target.result)
       } else {
         $("#documentUpload2")
        .attr('src', e.target.result)  
       }
    };

    reader.readAsDataURL(input.files[0]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<head></head>

<body>
  <ul>
    <li>
      <input id="input1" type='file' onchange="readURL(this,1);" />
      <img id="documentUpload1" document-up src="#" alt="first image" />
    </li>

    <li>
      <input id="input2" type='file' onchange="readURL(this,2);" />
      <img id="documentUpload2" document-up src="#" alt="second image" />
    </li>
  </ul>
</body>

</html>

Answer №2

If you're looking for a solution that can handle any number of images and any number of images per file-picker, this approach will do the trick.

Simply encase the #previewHolder div within a form and manage its submission accordingly.

function createNewElement(tag){return document.createElement(tag)}
function findElementById(id){return document.getElementById(id)}
function findAllByTag(tag,parent){return (parent == undefined ? document : parent).getElementsByTagName(tag)}


// Useful for HtmlCollection, NodeList, String types
function iterate(array, callback, scope){for (var i=0,n=array.length; i< n; i++)callback.call(scope, array[i], i, array);} // passes back necessary data

// Callback processes data retrieved from the .target.result field in the parameter passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL(fileObj);}


window.addEventListener('load', onDocumentLoaded, false);

function onDocumentLoaded(evt)
{
findElementById('addBtn').addEventListener('click', onAddButtonClicked, false);
}


/* HTML below function needs to create - Skip img creation since it's generated when files are picked */
/*
<div class='item'>
<img height='100px' width='100px'/><br>
<input type='file'/>
</div>
*/
function onAddButtonClicked(evt)
{
var wrapper = createNewElement('div');
wrapper.className = 'item';
//var img = createNewElement('img');
//img.style.height = '100px';
//wrapper.appendChild(img);

var input = createNewElement('input')
input.type = 'file';

// Enable multiple selection for file inputs
// input.multiple = 'true';

input.addEventListener('change', onFileChanged, false);
input.name = 'inputFiles[]';// Include [] so PHP can retrieve all files
wrapper.appendChild(input);

findElementById('previewHolder').appendChild(wrapper);
}

function onFileChanged(evt)
{
var numFiles = this.files.length;
var itemWrapper = this.parentNode;
var fileInput = this;

if (numFiles === 0)
{
// No files chosen, remove preview/file-picker element
var previewHolder = itemWrapper.parentNode;
previewHolder.removeChild(itemWrapper);
}
else
{
// Remove existing images
while (findAllByTag('img', itemWrapper).length != 0)
itemWrapper.removeChild( findAllByTag('img', itemWrapper)[0] );

iterate(this.files, loadAndPreviewImage);

function loadAndPreviewImage(fileObj)
{
loadFileObject(fileObj, onFileObjLoaded);

function onFileObjLoaded(evt)// Retrieve data using evt.target.result
{
var img = createNewElement('img');
img.style.height = '100px';
img.src = evt.target.result;
itemWrapper.insertBefore(img, fileInput);
}
}
}
}
.item
{
border: solid 1px black;
border-radius: 6px;
padding: 4px;
}
.button:hover
{
background-color: #b0ffb0;
cursor: pointer;
}
<div id='previewHolder' style='width: 200px'>
<div class='button' id='addBtn' style='text-align:center;padding: 4px'><svg xmlns="http://www.w3.org/2000/svg" height="32" width="32" viewBox="0 0 32 32">
<g transform="translate(0 -1020)" stroke="#00c03b" fill="none">
<circle cx="16" cy="1036" r="14.5" stroke-width="2.998"/>
<path d="m8 1036h16" stroke-linecap="round" stroke-width="3"/>
<path d="m16 1044v-16" stroke-linecap="round" stroke-width="3"/>
</g>
</svg></div>
</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

Contrasting loading data from an empty state and having no items present

On my web page, I pull items from an API and display them. The API request is made in the created hook. I need to display a [loading] message while waiting for the API response, and a [no items] message if the loading is complete but there are no items ava ...

Using Angular 4 for HTML 5 Drag and Drop functionality

I have been working on integrating native HTML 5 drag & drop functionality into my angular application. While I have successfully implemented the drag and dragOver events, I am facing an issue with the drop event not firing as expected. Here is the snipp ...

The Bootstrap popover fails to display

I am trying to display a popover on my website, but I am unable to see it. CODE echo ' <a data-toggle="popover" data-trigger="hover" data-html="true" data-placement="top" ...

A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected. I attempted binding the cl ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

Ways to toggle the display of a div depending on various radio button selections

Currently, I am working on a project using HTML along with Bootstrap and Jquery. My objective is to dynamically hide a div based on the selection of multiple radio buttons without requiring a submit button. The code snippet that I have provided below works ...

Storing a webpage in HTML with the use of @import function in CSS

I'm looking to save an entire HTML page, but I'm running into an issue with the CSS file that includes the line: import url('someOtherCss.css'); When attempting to save the page using Firefox or Chrome with 'File->Save Page a ...

Subrouter response yields a 404 error code

I have a router file named ping.js located in the http/api directory: var express = require('express'); var router = express.Router(); router.get('/ping', function (req, res) { res.send("You have accessed /api/ping"); }); module. ...

Discover which students have conflicting schedules with themselves

To put it simply, my question involves a table display where student numbers (USN) are concatenated in groups and the entire row is displayed using a foreach loop. Row 1: Subject 1 - 22/07/2015 - 08:00 - 1XX10XX086, 1XX10XX087, 1XX09XX088 Row 2: Subject ...

What is the proper way to add an object to an array without cloning or passing it by reference?

My issue is with a property called 'tiles' in a class that holds information about the state of a checkers board game. Each time I make a legal move or start the game, I want to push this property to an array named 'moves'. However, the ...

JavaScript array manipulation

I am working with an array of objects that have a year and count property like this: [{year: "1920", count: 0}, {year: "1921", count: 2}, {year: "1925", count: 0}, {year: "1930", count: 21}, ....] My goal is to popu ...

Images of varying sizes aligned at the bottom of cards, organized in rows with pure CSS styling

I am working on a layout that involves a container with "cards": images positioned above with related text below. Here's an example: <div class = "cards"> <div class = "card"> <div class = "image-wrap"> <img src= "im ...

Tips for effectively using $interval for ongoing polling in AngularJS?

Within my Angular codebase, I have implemented long polling functionality using the following code snippet: var request = function() { $http.post(url).then(function(res) { var shouldStop = handleData(res); if (!shouldStop()) { ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

Encountering issue with Konva/Vue-Konva: receiving a TypeError at client.js line 227 stating that Konva.Layer is not a

I am integrating Konva/Vue-Konva into my Nuxtjs project to create a drawing feature where users can freely draw rectangles on the canvas by clicking the Add Node button. However, I encountered an error: client.js:227 TypeError: Konva.Layer is not a constr ...

Formatting tables

Below is the table structure that I have. I attempted to insert empty tds divs in order to achieve the formatting shown in the image, but I have not been successful. Any suggestions or ideas would be greatly appreciated. <table border="0" cellpadding=" ...

Unable to access an HTML element using refs within the render() method

Currently, I am working on developing a graphics editor using ReactJS. One of the main components in my project is the Workspace component. This particular component is responsible for drawing objects on the canvas element. The Workspace component is imple ...

IE9 Z-index Issue

Currently, I am facing an issue with two images not displaying correctly on a website that I am working on. The problem seems to be specific to IE 9, as other browsers are working fine. The trouble arises when I try to create a slideshow with a shadow back ...

What causes the failure of data reaching the server?

I need to make updates to some details in a few tables, but I'm having trouble getting it to work. Can someone help me figure out what's wrong? <body> <form class="" action="view_update_emp.php" method="post& ...

I am attempting to retrieve a data key from an api, but I am encountering keys with special characters such as hyphens. How can I properly incorporate them into my code?

I encountered an issue with some keys in the format of "something-something" that the JS code currently restricts me from using. I am seeking a workaround for this limitation. One specific example is when I need to reset a React state. Below is a line of ...