How to preview several different images?

Asked

Viewed 400 times

3

How do I preview several different images from different inputs?

Here’s an example of how I wanted it to stay

HTML

<div class="col">
    <input type="file" class="custom-file-input" name="arquivo" id="files" onchange="preview(this);">
    <div class="preview-img">
        <img id="preview_image" alt="" src="">
    </div>
</div>

<div class="col">
    <input type="file" class="custom-file-input" name="arquivo" id="files" onchange="preview(this);">
    <div class="preview-img">
        <img id="preview_image" alt="" src="">
    </div>
</div>

<div class="col">
    <input type="file" class="custom-file-input" name="arquivo" id="files" onchange="preview(this);">
    <div class="preview-img">
        <img id="preview_image" alt="" src="">
    </div>
</div>

Javascript

function preview(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#preview_image')
            .attr('src', e.target.result)
                                .width(100)
                                .height(100)
        };
        reader.readAsDataURL(input.files[0]);
    }
}

http://jsfiddle.net/rahnY/2/

  • 2

    Hello Altemberg. I edited the question to include the relevant code right here. It is always important to do this, so that people do not need to leave the site to understand the problem. In addition, external links may be unavailable. Please take this into account in the next questions, and good learning!

1 answer

3


You need to make this change:

Of:

$('#preview_image')

for

$(input).closest('.col').find('img.preview_image')

and remove duplicate Ids here: <img id="preview_image" alt="" src=""> changing ID to class like this: <img class="preview_image" alt="" src="">.

Example: http://jsfiddle.net/X8LD5/

Switching from duplicate ID’s to classes has to be in order not to have invalid HTML. What was happening is that the code would always fetch the first element with the ID preview_image.

The change I made in jQuery is more interesting and is related to the element input who was changed by going to get the closest parent element with the class col and then descend on the DOM in search of the img with class preview_image, descending from that class element col.

  • 1

    Thanks, Sergio. This can even serve me for future problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.