How to preview several different images?

3

How do I preview several different images from different inputs?

Here is an example of how I wanted it to be

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]);
    }
}

link

    
asked by anonymous 06.06.2014 / 20:29

1 answer

3

You need to make this change:

From:

$('#preview_image')

for

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

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

Example: link

Changing duplicate ID's to classes even has to be to not 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 it is relative to the element input that has been changed by fetching the parent element closest to the class col and then descending into the DOM in search of img with the class preview_image , descending from this element with class col .

    
06.06.2014 / 20:34