Add multiple images to various div containers

I am facing a challenge with my code as I am trying to upload and display two different files inside of two different divs using two buttons. Currently, my code is only working for one image. How can I modify the code to handle two images successfully? Any help is appreciated!

Here is my existing code:

HTML:

<div class="span12">
    <span class="btn btn-default btn-file"> Browse 1 <input type="file" onchange="readURL(this);"></span>
            <span class="btn btn-default btn-file"> Browse 2 <input type="file" onchange="readURL(this);"></span>

    <div class="place-image" id="myimage">
    <div class= "place-content" id="myimage2" onkeypress="return (this.innerText.length <= 16)">
            <p contenteditable="true">SALE<br>40%</p>
            </div>  
        </div>

JavaScript:

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

        reader.onload = function (e) {
            $('#myimage').css('background', 'transparent url('+e.target.result +') left top no-repeat');
        }

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

Answer №1

To enhance the functionality, include data-preview="preview_div_id" in each input tag. Then, within the onload function, replace $('#myimage') with

$('#' + $(input).data("preview"))
.

Here is an example:

<div class="span12">
    <span class="btn btn-default btn-file"> Browse 1 <input type="file" onchange="readURL(this);" data-preview="myimage"></span>
            <span class="btn btn-default btn-file"> Browse 2 <input type="file" onchange="readURL(this);" data-preview="myimage2"></span>

    <div class="place-image" id="myimage">
    <div class= "place-content" id="myimage2" onkeypress="return (this.innerText.length <= 16)">
            <p contenteditable="true">SALE<br>40%</p>
            </div>  
        </div>


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

        reader.onload = function (e) {
            $('#' + $(input).data("preview")).css('background', 'transparent url('+e.target.result +') left top no-repeat');
        }

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

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

Top approach for creating/previewing a website using PHP, CSS, and MYSQL

When creating a website that will eventually be hosted on a remote server, what is the most effective way to code and test? Here are some examples of what I mean: - Develop locally on your computer and access files from there. Should libraries and databa ...

The issue with the ng-click property not triggering arises when it is assigned to a button that is generated dynamically

I need to construct a table dynamically based on the results returned from SQL. In this scenario, populating the table with the start time, end time, and user is straightforward: var StartTime = document.createElement('td'); var EndTime = docume ...

What is the best way to implement "computeIfAbsent" or "getOrElseUpdate" functionality for a Map in JavaScript?

If we assume that m represents a Map<number, V> for a certain type V k is a number, how can we create an expression that can either retrieve an existing V for the key k, or generate a new v: V, insert it into the map for the key k, and result in v ...

Exploring touch interactions using D3.js and TUIO

I'm currently facing a challenge with implementing multi-touch functionality and the d3.slider in my D3 Map. You can see the current state of my project in this video. With the d3 slider, I can spawn points and navigate around the map using touch even ...

Disabling the scaling feature in IE11's WebBrowser control: A step-by

After investing 48 hours into resolving this particular issue, I am reaching out to the knowledgeable StackoverFlowers community for assistance. My current project involves developing an application for large 27-inch multi-touch screens using C# 4.5. Withi ...

Exploring Joomla: Customizing Template Options for Individual Menu Items

Hey there! I'm currently working on a website using Joomla 1.5 and I'm wondering if it's possible to load different template options based on the menu item ID. I came across the Gantry Framework (http://www.gantry-framework.org) which allow ...

The correct assertion of types is not carried out during the initialization of generics through a constructor

I am encountering a minor issue with TypeScript, and I am uncertain whether it is due to a typo on my part or if TypeScript is unable to correctly infer the types. Let me provide all the necessary code to replicate the problem: interface IRawFoo { type: s ...

Perform a postback within a jQuery UI dialog box

Despite many solutions being available from various Stack Overflow users, none seem to be effective for me. In aspx <asp:Button ID="btnConfirm" ClientIDMode="Static" runat="server" Text="Confirm" OnClick="btnConfirm_Click"/> <script type="text/ ...

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

Stop Form Submission in Bootstrap 5

I require assistance with identifying the issue in the JavaScript code provided below. I am working with a Bootstrap 5 form where the submission is not being prevented if the fields are left blank or invalid. While the HTML/CSS validation works correctly f ...

display the JSON response using jQuery

Having an issue with printing the response JSON using a message alert. Here is the script I am using: $.ajax({ headers: { "Accept" : "application/json", "Content-Type": "application/json" }, url: "http:/ ...

Make the card change to gray when clicked using Bootstrap

Is it possible to achieve a common function in an infinite list using HTML, CSS, JS, jQuery (on the user's side) where an item will be grayed out after being clicked? How can we implement this effect? 1.) When the user clicks on the card element htt ...

Firefox users may notice that the pop-up video player appears in unusual locations on their screen

I'm encountering an issue with a pop-up video player that is triggered by an "onClick" event in HTML elements. The problem arises when there are multiple video players on the same page - in Firefox, the first video loads at the bottom of the page, req ...

What is the best way to center a menu for a cohesive and balanced appearance?

I am encountering an issue with my design. I am attempting to center-align a menu, but I want it to appear uniform and consistent. I want it to resemble the layout shown in the image link below. https://i.sstatic.net/D3Rep.png I cannot understand why my ...

Unable to generate webpage source code

Having some trouble with my Next.js project as I'm using getStaticProps and getStaticPath to build a page, but unfortunately, the HTML is not being generated in the page source. This issue is causing problems with SEO, and I haven't implemented r ...

Retrieve information from an ajax response in XML format

AJAX Call Code Example $.ajax({ url: '/services/LTLGadgetV2.aspx', type: 'Get', success: function (result) { console.log( result); } }); The response in the console: Sample XML <RateResults xmlns ...

Retrieving a designated value from a jquery object sent via an ajax call

Currently, I have a setup where clicking on a link sends the link's ID via AJAX to a coldfusion page for querying and returning an object. The jquery function in use is: $(".thelink").click(function(){ var link_id = $(this).attr("id"); var ...

Retrieving text from Node.js with the help of regular expressions

I need to extract testcase ids from a list of testcases with titles. Each title includes an id and a description. I want to extract only the id. Here are some examples: TC-ABC-98.1.010_1-Verify the layout credit page TC-RegPMP-1.1.001_2-Verify the [MangerD ...

Turn off the automatic resizing of Internet Explorer 11 to fit the width of the viewport - IE11

Is there a way to stop Internet Explorer 11 from automatically zooming to fit the viewport width? I need the browser to respect my max-width rule and not scale the content to fill the entire width of the viewport on its own. This issue is happening in IE ...

When using Node.js, Express.js, and MongoDB, ensure that the route.post() function is provided with proper callback functions instead of

I've been working on setting up a MEAN (MongoDB, Express, Node.js, Angular 6) application. I'm trying to post user signup form data to a MongoDB database, but I keep getting an error message. This is my first time working with the MEAN stack and ...