Hkm Sadek Hossain Hkm Sadek Hossain - 4 months ago 9
Javascript Question

javascript's window.preview function

I am trying to implement the following code which works fine for one input file but I am looking to use same thing using two forms and two different divs.



window.preview = function(input) {
if (input.files && input.files[0]) {
$(input.files).each(function(){
var reader = new FileReader();
reader.readAsDataURL(this);
reader.onload = function(e) {
$("#messages-list").append("<li class='text-message-img'><img class='thumb' src='" + e.target.result + "'></li>");
}
});
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="picture-upload">
<span>
<img src="images/icons.png">
Click to upload
</span>
<input class="upload" type=file onchange="preview(this);" accept="image/*" value="">
</form>





But the problem is I want to use two form that shows in different div.
How can I select two different form input and show the result in two different divs?

mhu mhu
Answer

You could pass the id of the target element to the preview function:

window.preview = function(input, element) {
    if (input.files && input.files[0]) {
        $(input.files).each(function(){
            var reader = new FileReader();
            reader.readAsDataURL(this);
            reader.onload = function(e) {
                $(element).append("<li class='text-message-img'><img class='thumb' src='" + e.target.result + "'></li>");
            }
        });
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="picture-upload">
    <span>
        <img src="images/icons.png">
        Click to upload
    </span>
    <input class="upload" type=file onchange="preview(this, '#messages-list');" accept="image/*" value="">
</form>