Having Multiple File Inputs [type=file] in one webpage

Is it possible to have two separate inputs for uploading images, each setting a different background image in a div?

The second file input is:

<input type='file' id='getval' name="logo" />

I want this file to be set as the background image of the following div:

<div id="logo"></div>

In summary, here's what I am trying to achieve:

document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
   var file = document.getElementById("getval").files[0];
   var reader = new FileReader();
   reader.onloadend = function(){
      document.getElementById('adXL').style.backgroundImage = "url(" + reader.result + ")";        
   }
   if(file){
      reader.readAsDataURL(file);
    }else{
    }
}
h2 {
font-size: 14px;
margin: 14px 0 3px;
}

#adXL{
   background-image:url('');
   background-size:cover;
   background-position: center;
min-height: 200px;
   width: 100%;
  min-width: 0;
   border: 0px solid #ddd;
  display: flex;
  flex-direction: column;
  margin: 20px 0 0 0;
  background-color: #eee;
}


#logo{
   background-image:url('');
   background-size:cover;
   background-position: center;
  min-width: 0;
  width: 150px;
  min-height: 50px;
  display: flex;
  flex-direction: column;
  margin: 20px;
  background-color: #ccc;
}
<h2>Background Image</h2>
<input type='file' id='getval' name="background-image" />
<h2>logo</h2>
<input type='file' id='getval' name="background-image" />

<div id='adXL'>
<div id='logo'>
</div>
</div>

Answer №1

It's advisable to avoid re-using IDs in HTML for better code organization.


document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
   var file = document.getElementById("getval").files[0];
   var reader = new FileReader();
   reader.onloadend = function(){
      document.getElementById('adXL').style.backgroundImage = "url(" + reader.result + ")";        
   }
   if(file){
      reader.readAsDataURL(file);
    }else{
    }
}

document.getElementById('getval2').addEventListener('change', readURL2, true);
function readURL2(){
   var file2 = document.getElementById("getval2").files[0];
   var reader2 = new FileReader();
   reader2.onloadend = function(){
      document.getElementById('logo').style.backgroundImage = "url(" + reader2.result + ")";        
   }
   if(file2){
      reader2.readAsDataURL(file2);
    }else{
    }

Answer №2

Make a change to your input file by adding the 'change' attribute instead of using eventListeners, then call the readURL() function. This way, you can pass parameters and reuse the function.

function readURL(input,output){
   var file = document.getElementById(input.id).files[0];
   var reader = new FileReader();
   reader.onloadend = function(e){
      document.getElementById(output).style.backgroundImage = "url('" + reader.result + "')";        
   }
   if(file){
      reader.readAsDataURL(file);
    }else{
    }
}
h2 {
font-size: 14px;
margin: 14px 0 3px;
}

#adXL{
   background-image:url('');
   background-size:cover;
   background-position: center;
min-height: 200px;
   width: 100%;
  min-width: 0;
   border: 0px solid #ddd;
  display: flex;
  flex-direction: column;
  margin: 20px 0 0 0;
  background-color: #eee;
}


#logo{
   background-image:url('');
   background-size:cover;
   background-position: center;
  min-width: 0;
  width: 150px;
  min-height: 50px;
  display: flex;
  flex-direction: column;
  margin: 20px;
  background-color: #ccc;
}
<h2>Background Image</h2>
<input type='file' id='getval' onchange="readURL(this, 'adXL')" name="background-image" />
<h2>logo</h2>
<input type='file' id='getval' onchange="readURL(this, 'logo')" name="background-image" />

<div id='adXL'>
<div id='logo'>
</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

Simple HTML files on a local server are having trouble loading images and JavaScript, yet the CSS is loading

Having worked in web design for quite some time, I recently began working on a basic Angular app that is meant to be very simple. For this project, I am only using the angular files and a single html file as the foundation. As I started setting up the bas ...

Utilize Javascript to access Django Rest Framework API and obtain a Token

I've successfully set up an API with Django Rest Framework that functions well when accessed through cURL, HTTPie, or the browsable API. The API utilizes token authentication, requiring initial credentials to obtain a token. To achieve this using HTTP ...

Display unique JQuery special characters

I'm looking to modify this specific text Hello Mr ABC so that it appears as: Hello "Mr ABC". The text Mr ABC includes a unique non-printable character " ". P.S: Where can I find more information on this topic? ...

The image upload failed: the server could not locate the requested URL

I am completely new to working with Flask, and I'm currently in the process of creating a basic image uploading application. After comparing my code with various tutorials on how to build similar apps, it seems like everything is in place. However, w ...

What is the best way to navigate through the underlying MatDialog while the MatSelect is active?

When attempting to customize the scroll behavior of a MatSelect in a regular page, I discovered that using the MAT_SELECT_SCROLL_STRATEGY injection token with the NoopScrollStrategy allows for scrolling the underlying page while keeping the MatSelect stati ...

Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...distfxcoreservermain.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or np ...

Employ the CSS pseudo-element :before within a UL element to generate a vertical line

I'm currently working on a vertical menu with the capability of having submenus. My aim is to include a vertical line using CSS pseudo-element ::before along with border. The challenge I'm encountering is that the CSS is applying to the entire m ...

Creating a JavaScript function in Selenium IDE specifically for today's date

Just starting out with Selenium IDE and looking to build a set of regression scripts for our department. Trying to insert today's date plus 180 days into a field using a JavaScript function. If anyone can guide me on how to write this function, I wou ...

What is the best way to dynamically validate the fields and generate an array?

Currently in my Angular application, I've successfully implemented a pivot table using pivot.js. Now, I am faced with the task of loading all the indexes from elastic search whenever the user switches the index. Once the index is changed, the corresp ...

Concealing HTML content with a modal overlay

There are security concerns with my authentication overlay modal, especially for users familiar with CSS and HTML. Is there a way to hide the HTML behind the modal so it doesn't appear in the page source? The code below is just an example of a modal ...

React-virtualized list experiencing performance problems due to react-tether integration within its elements

Description I need help with a challenging issue. I have a long list of items displayed in a react-virtualized VirtualScroll. Each item on the list contains many elements, including one that triggers a context menu. I'm using react-tether to attach t ...

Utilize the push method to form a new array

var teamMembers = [ ['John D. Adams', '1959-1967', 'Ohio'], ['Dawson Mathis', '1971-1981', 'Georgia'], ]; To generate this dynamically, I am implementing the code below: var data = ne ...

Enhancing jQuery Component while making an Ajax request

When a user clicks a button, I am making an ajax call to send out multiple emails. My goal is to update a "Please wait..." div before and after the call with status updates, as well as report any errors that may occur. However, I have encountered an issue ...

Harnessing the power of data within different components

In my setup, I have two vital components in play. The initial one is responsible for presenting a list of items, while the second dictates the design and layout of these items. These items reside in an array located within the app.vue file. Here lies my p ...

Combining the background images of two separate <div> elements results in a deeper shadow effect than when they are individually displayed

Encountering an issue with overlapping background images that results in a darker shadow where they intersect, causing an uneven appearance. The problem arises with a flexible height box containing semi-transparent background images designed to create att ...

Save the data in Redux and access it back

I am currently using material-ui-dropzone to upload an array of files and store them in redux However, when I try to retrieve the file from the redux state, it is not recognized as type "File" and appears differently in devtools https://i.stack.imgur.com ...

Ways to transmit information from a React application to a Node server

As a Nodejs beginner, I am using the rtsp-relay library for live streaming. Currently, it is working in the frontend when the URL is included in the server proxy object like this: rtsp://.....@..../Stream/Channel/10. However, I want users to be able to inp ...

The inability of Chrome and Firefox browsers to open Windows folders directly from a hyperlink is a common

My link is directing to a Windows folder using its directory path. Surprisingly, it works perfectly fine in Internet Explorer but fails to work in Chrome and Firefox. How can I resolve this issue? The structure of my link looks like this: <a href="&bs ...

Highlighting syntax on the server side

I have some code blocks that I want to emphasize. Currently, I am using prismjs for this purpose. However, when I try to highlight several code blocks, the page takes more than 5 seconds to load on my somewhat slow PC. Interestingly, if I remove the prism ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...