"Previewing multiple images before uploading for a better visual experience

I am working on a project to enable previewing multiple images, but I encountered an issue. My current code only works when uploading 2 images. I want the preview to work for as many images as the user uploads.

Here is the relevant JavaScript code:

var abc = 0; //Global increment variable

$(document).ready(function() {


$('#file').click(function() {
    $(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
            $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
            $("<br/><br/>")
            ));
});

$('body').on('change', '#file', function(){
        if (this.files && this.files[0]) {
             abc += 1;

            var z = abc - 1;
            var x = $(this).parent().find('#previewimg' + z).remove();
            $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");

            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);

            $(this).hide();
            $("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
            $(this).parent().parent().remove();
            }));
        }
    });

function imageIsLoaded(e) {
    $('#previewimg' + abc).attr('src', e.target.result);
};

$('#upload').click(function(e) {
    var name = $(":file").val();
    if (!name)
    {
        alert("First Image Must Be Selected");
        e.preventDefault();
    }
}); 
});

If you can help me with this issue, please check out my FIDDLE.

Answer №1

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Upload images using Jquery</title>
        <script type="text/javascript" src="jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                var storedImages = [];      
                $('#myimages').on('change', function() {
                    $('#messages').html('');
                    var myimages = document.getElementById('myimages');
                    var files = myimages.files;
                    var i=0;
                    for (i = 0; i<files.length; i++) {
                        var reader = new FileReader();
                        var image=files[i];
                        if(image.type.match('image.*')){
                            storedImages.push(image);
                            reader.onload = (function(image) {
                                return function(e) {
                                    $('#uploadedimages').append('<tr class="imageinfo"><td><img width="80" height="70" src="'+e.target.result+'"/></td><td>'+image.name+'</td><td>'+Math.round((image.size/1024))+'KB</td><td><a href="" class="lnkcancelimage" image="'+image.name+'" title="Cancel"><img src="delete.png" width="34" height="34"/></a></td></tr>');
                                };
                            })(image);
                            reader.readAsDataURL(image);
                        }else{
                            alert('the file '+image.name+' is not an image<br/>');
                        }
                    }
                });

                $('#uploadedimages').on('click','a.lnkcancelimage',function(){
                    $(this).parent().parent().html('');
                    var image=$(this).attr('image');
                    for(var i=0;i<storedImages.length;i++) {
                        if(storedImages[i].name == image) {
                            storedImages.splice(i,1);
                            break;
                        }
                    }
                    return false;
                });

                $('#lnkupload').click(function(){
                    var data = new FormData();
                    var i=0;
                    for(i=0; i<storedImages.length; i++) {
                        data.append('images'+i, storedImages[i]); 
                    }

                    if(i>0){
                        $.ajax({
                            url: 'load.php',
                            type: 'POST',
                            contentType: false,
                            data: data,
                            processData: false,
                            cache: false
                        }).done(function(msg) {
                            storedImages = [];
                            if(msg){
                                alert(msg);
                            }else{
                                $('#messages').html('Images uploaded successfully');
                            }
                        }).fail(function() {
                            alert('error');
                        });
                    }
                    return false;
                });

            });
        </script>
    </head>
    <body>
        <div id="wrapper">
            <label><strong>Uploading multiple images</strong></label>
            <input id="myimages" type="file" name="myimages[]" multiple="multiple" />
            <a href="" id="lnkupload">Upload</a>
            <table id="uploadedimages">
                <tr><th>Image</th><th>Name</th><th>Size</th><th>Actions</th></tr>
            </table>
        </div>
    </body>
</html>

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

Enhance User Experience with React JS Multi-Select Dropdown Feature

I am dealing with 4 select dropdowns. The values selected should not be available in the remaining dropdown lists. Here is an overview of my state: this.state = { selectedDropdownArray: {}, dropdownArray: ['select', '1', &apos ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

Display the cost in a dynamic label that adjusts accordingly as the user modifies its value

Currently, I am facing the following issue. I am in the process of creating a form where users can choose from a selection of products they want to order. The form currently looks like this: <input type="number" class="bestelformulier" name="PizzaMaga ...

IE disregard min-height property of flex container

After researching, it appears that using the standardized flex terms should work with IE10/IE11. I have a container div with 2 child divs. Both child divs are smaller than 400px, so there should always be enough space for the justify-content: space-betwe ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

Limit the ng-repeat results based on search input using a transformation filter

I am currently working with an array of records that are being displayed in an HTML table with filters in the header. However, I have encountered an issue where some values are transformed by filters, causing the ng-repeat filter to fail. <table class= ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

A step-by-step guide on extracting multiple data entries from JSON that correspond to an array of IDs

Within my JavaScript code, I am working with a JSON dataset containing posts, each with a unique post_id. I also have an array of specific post_ids that I want to use to extract certain posts from the main dataset. const dataset = [ {post_id: 1, titl ...

Adjusting screen size to match different resolutions

After uploading mrandmrsmagic .com website, a few issues were noticed. The site appears fine when maximized, but only half is shown when minimized. The absence of a scroll bar could be causing this display problem. Five different background images were use ...

Creating a search dictionary in MongoDB for text validationDiscover how to implement a search dictionary in MongoDB

I have a project in mind to create a spell-check dictionary for text verification. The dictionary contains 20,000 words. With my Meteor application, the goal is to input the text, split it into words, and verify each word against the dictionary. However, ...

Challenges in integrating callbacks effectively in node.js scripts

I am currently working on a node.js function called process() that is meant to return a value when it is invoked. However, I am encountering difficulties in creating a callback for the process(). The expected behavior is for the value to be returned from p ...

Automatically enlarge the container when the text area contains text

I am currently developing a blog using PHP / MySQL and have successfully implemented an edit post function. Upon clicking the "Edit" button, the page refreshes (URL changes), the <div> expands, and the content of the post being edited is displayed i ...

What is the best way to retrieve a string from a lambda expression?

I am trying to call the function myFunction() and retrieve the source._id value, but I'm encountering issues with the current code. Even though source._id is correctly filled, I am unsure of how to successfully return it in its entirety. Ideally, some ...

What are the benefits of using PHP heredoc to create straightforward HTML code?

I've recently taken over the reins of a website and am looking to implement some changes. It's interesting because everything is structured using heredoc PHP scripts, yet there doesn't seem to be any actual PHP processing happening within th ...

What is the method for ensuring a p element is only as wide as necessary when it wraps within a parent div with a specified hardcoded width?

Is there a way to adjust the width of the p-element in my example below based on the text inside without affecting the normal line break behavior, using only CSS if possible? It appears to be ignoring wrapping and is too wide: https://i.stack.imgur.com ...

Setting up Scss and purgeCss configuration in Next.js custom postCSS configuration: A step-by-step guide

My current project is using Scss in combination with Bootstrap for design. I have implemented purgeCss to remove unused Css, and customized my postcss.config.js file as follows: module.exports = { plugins: [ "postcss-flexbugs-fixes", [ " ...

What is the best way to determine when an IndexedDB instance has finished closing?

In the world of IndexedDB, the close method operates asynchronously. This means that while close finishes quickly and returns immediately, the actual connection closure happens in a separate thread. So, how can one effectively wait until the close operatio ...

Interactive Button Animation using Three.js

After importing a Mesh element into three.js from an fbx file, I am looking to enhance it with an effect similar to that of a clickable button. I am aiming to achieve the same pushable button effect as demonstrated in the first button style found on http ...

Enhanced hierarchical organization of trees

I came across this code snippet: class Category { constructor( readonly _title: string, ) { } get title() { return this._title } } const categories = { get pets() { const pets = new Category('Pets') return { ge ...

Is it possible to execute the 'min' task in Grunt multiple times?

Is there a way to execute a task twice with different configurations in Grunt? For example, I have two groups of source files in my project that I want to minify into separate output files. The file structure looks like this: project srcA file ...