Enable the ability to upload multiple images on a single page using droparea.js

I am currently utilizing droparea js for uploading images. However, I have encountered an issue where if I try to upload an image in one of the upload menus, it ends up changing all four upload menus simultaneously.

<div class="col-md-12">
                <div class="droparea">
                <img src="http://placehold.it/200" class="file_preview">
            </div>
            <input type="file" name="file" id="file" accept="image/*" style="display: none;">
<div class="col-md-12">
                <div class="droparea">
                <img src="http://placehold.it/200" class="file_preview">
            </div>
            <input type="file" name="file" id="file" accept="image/*" style="display: none;">
<div class="col-md-12">
                <div class="droparea">
                <img src="http://placehold.it/200" class="file_preview">
            </div>
            <input type="file" name="file" id="file" accept="image/*" style="display: none;">
<div class="col-md-12">
                <div class="droparea">
                <img src="http://placehold.it/200" class="file_preview">
            </div>
            <input type="file" name="file" id="file" accept="image/*" style="display: none;">
<script src="js/droparea.js"></script>
<script>
  $(document).ready(function(){
$('.droparea').droparea({
            url: 'server.php',
            success: function( server_return, name, uploaded_file )
            {
                $('.droparea').after( $('<p />').html( 'File sent: <b>' + name + '</b>' ) );

                var oFReader = new FileReader();

                oFReader.readAsDataURL( uploaded_file );
                oFReader.onload = function (oFREvent)
                {
                    $( '.file_preview' ).animate({opacity: 0}, 'slow', function(){
                        // change the image source
                        $(this)
                            .attr('src', oFREvent.target.result).animate({opacity: 1}, 'fast')
                            .on('load', function()
                            {
                                $('.statusbar').css({
                                    width: $('.droparea').outerWidth(),
                                    height: $('.droparea').outerHeight()
                                });
                            });

                        // remove the alert block whenever it exists.
                        $('.droparea').find('.statusbar.alert-block').fadeOut('slow', function(){ $(this).remove(); });
                    });
                };
            }
        });
});


</script>

I would like to share this on jsfiddle, but unfortunately, I cannot find the online resources (js and css) for the droparea plugin.

When attempting to upload an image in any menu except the first one, the result always appears in the first menu. To address this, I changed from id="file-preview" to class="file-preview", resulting in the same display for all. Can someone guide me on how to enable uploading different images in each menu?

Answer №1

I am not very experienced with droparea, but it seems like you need to create a separate instance for each rather than just one .droparea() instance. You could try something like this:

$('.droparea').each(function(){
   $(this).droparea()
});

In addition, you may require the following code snippet:

$('.droparea').each(function(){
 $(this).droparea({
            url: 'server.php',
            success: function( server_return, name, uploaded_file )
            {
                $('.droparea').after( $('<p />').html( 'File sent: <b>' + name + '</b>' ) );

                var oFReader = new FileReader();

                oFReader.readAsDataURL( uploaded_file );
                oFReader.onload = function (oFREvent)
                {
                    $( '.file_preview' ).animate({opacity: 0}, 'slow', function(){
                        // change the image source
                        $(this)
                            .attr('src', oFREvent.target.result).animate({opacity: 1}, 'fast')
                            .on('load', function()
                            {
                                $('.statusbar').css({
                                    width: $('.droparea').outerWidth(),
                                    height: $('.droparea').outerHeight()
                                });
                            });

                        // Remove the alert block if it exists.
                        $('.droparea').find('.statusbar.alert-block').fadeOut('slow', function(){ $(this).remove(); });
                    });
                };
            }
        })
   })

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

Is it possible to incorporate a Node.js library into an HTML document?

I am working on an HTML file where I want to incorporate the nodemailer library to handle email sending. Although in nodejs, I can easily include var nodemailer = require('nodemailer') at the beginning of the script section of my HTML file, it ap ...

Tips for effective page management

After creating a navbar in my project, I've come to the realization that it requires a component for each page and subpage. This seems redundant especially when dealing with multiple navigation options like shown in this image. Is it necessary to crea ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Exploring the power of JQuery's $.post() function and the magic

In order to utilize the GroupMe API (), the following command is required: $ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN I ...

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

The function res.send is unavailable and errors are not being properly managed

I encountered a peculiar error while using my function to create users in my mongoose database. Despite the user being successfully created, I am facing an issue where res.send is not functioning as expected, resulting in no response and instead, an error. ...

The width property in Bootstrap is not functioning properly in .NET Core 6

I've exhausted all my options, including documentation and the last 10 stack overflow answers, but nothing seems to be working. I even tried using: <meta name="viewport" content="width=device-width, initial-scale=1"> I attem ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

Execute the function when the control becomes visible

Currently, I possess an input control: <input id="someID" class="form-control" type="text" name="SomeData" data-ng-model="vm.SomeData"> I have a requirement to set the initial value of vm.SomeData upon user scrolling down to this control. As a begi ...

Unable to retrieve the .attr() from a button that was created using handlebars

I am currently working on developing a web scraper as part of a homework task that involves using Express, Mongoose, Cheerio/axios, and Handlebars. In my "/" route, I retrieve the Mongoose objects and use Handlebars to display them on the page in individua ...

Adaptable positioned picture

I'm trying to figure out how to make a series of positioned images adjust to the window's dimensions. Should the images be relative and the page wrap absolute, or vice versa? I've been experimenting on jsfiddle but can't seem to get it ...

What steps can be taken to prolong the duration of a service?

As a newcomer to angularjs, I am struggling to find documentation or examples on how to extend a basic service in order to utilize its methods from other services. For example, consider the following basic service: angular.module('myServices', [ ...

Place a written message on an picture

<head> <style> .relative{position:relative; width:600px;} .absolute-text{position:absolute; bottom:1; font-size:12px; font-family:"vedana"; background:rgba(251,251,251,0.5); padding:10px 20px; width:10%; text-align:center;} </style> < ...

Waiting for all promises to resolve: A step-by-step guide

I need to make two different API calls and perform calculations based on the results of both. To wait for both promises to resolve, I am using Promise.all(). const getHashTagList = async () => { loader.start(); try { await getAllHashTag ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

Tips for displaying and concealing a toggle button based on screen size changes

My goal is to display my userlist without a toggle button by default when the screen is in full size, and only provide a toggle button when the screen is in mobile size to allow users to show/hide the list. Currently, I am utilizing the following code: & ...