RichardBlack
RichardBlack

Reputation: 13

Multiple Image Upload with previews each

Hello i am currently creating an image upload page where you can upload images one by one by each requirement. Currently it works with one preview.. How can i add another input type file where the image preview is separate from the first one? I did try it but it just replaces the past preview..

<form method="post" action="upload.php" enctype="multipart/form-data">

//first one
<input type="file" name="file" id="file" />
<span name = "preview1" id ="preview1"></span>
//second one
<input type="file2" name="file" id="file2" />
<span name = "preview2" id ="preview2"></span>

<input type="submit" name="submit" value="Upload"/>
</form>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function filePreview(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#preview1 + img').remove();
        $('#preview1').after('<img src="'+e.target.result+'" width="450" height="300"/>');
    }
    reader.readAsDataURL(input.files[0]);
    }
  }
    $("#file").change(function () {
   filePreview(this);
});
</script>

Upvotes: 1

Views: 61

Answers (1)

jor1s
jor1s

Reputation: 69

The problems in your code are in your css selectors.

$('#preview1 + img').remove();

You're removing the adjacent sibling <img> element directly after the element with id preview1.

$('#preview1').after(...)

And here you're inserting the new <img> element directly after the first file input (#preview1).

What you could do is using your function argument this (which refers to the right file input element, the one on which the change event fired).

Since you're already using jquery you could use the methods next and after in conjunction with your function argument input.

Here is your filePreview function reworked :

function filePreview(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $(input).next('img').remove();
            $(input).after('<img src="'+e.target.result+'" width="450" height="300"/>');
        }
        reader.readAsDataURL(input.files[0]);
    }
}

Hope it helps !

Upvotes: 1

Related Questions