Millhorn
Millhorn

Reputation: 3166

Issue uploading multiple images to a page with "upload" button...

I have a Fiddle here...

I've accomplished the ability to get an image to load below the upload button, however, how can I upload multiple images to the same page? There are three places where I've allowed the user to upload a specific image.

<div class="element-file" title="Do you want to add an image to the Accreditation Text?">
    <label class="title" style="font-weight: bold;">Add an image to the left of the Accreditation text<br>(Image will be resized to 100px by 100px)</label>

    <label class="medium" >
            <input type='file' onchange="readURL(this);" />
    </label>
        <p><strong>(Image will display below)</strong></p>
            <div style="max-width: 100px; height: auto; border:1px dashed black;">
                <img id="accred_image" src="accred" alt="" />
            </div>
</div>

And add an image to this area...

<div class="element-file" title="Do you want to add an image to the Accreditation Text?">
    <label class="title" style="font-weight: bold;">Would you like to add a logo image?</label>

    <label class="medium" >
            <input type='file' onchange="readURL(this);" />
    </label>
        <p><strong>(Image will display below)</strong></p>
                <div style="max-width: 140px; height: auto; border:1px dashed black;">
                    <img id="blah" src="" alt="" />
                </div>
</div>

This is my javascript, but when I upload an image, it places the same image in both spots. I thought this had something to do with the class I am uploading from, but creating the new class, doesn't seem to help at all.

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var reader = new FileReader();
        reader.onloadend = function() {
             $('#accred_image').attr('src', reader.result);
        }
        reader.readAsDataURL(file);        }
});

Upvotes: 2

Views: 96

Answers (1)

MarianaAFSilva
MarianaAFSilva

Reputation: 445

You need to find that is the img to update. Try this:

$("input").change(function(e) {

    var elemIMG = $(this).parent().parent().find('img'); // find the img to update

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var reader = new FileReader();
        reader.onloadend = function() {
              elemIMG.attr('src',reader.result); // update the img src
        }
        reader.readAsDataURL(file);        }
});

Upvotes: 2

Related Questions