3

I use jQuery to add form group dynamically:

<form>
    <div id="form-group-wrapper">
        <div class="row">
            <input class="userfile" name="userfile[]">
            <img src="default.png" class="preview-image" />
        </div>
    </div>
    <button type="submit">POST</button>
    <button type="button" id="copy-btn">Add new row</button>
</form>
<div id="hide-ele">
    <div class="row">
        <input class="userfile" name="userfile[]">
        <img src="default.png" class="preview-image" />
    </div>
</div>

jQuery is:

$('#copy-btn').click(function(){
    newOne = $('#hide-ele').html();
    $('#form-group-wrapper').append(newOne);
});

$(function() {
    $(".userfile").on("change", function() {
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return;

        if (/^image/.test( files[0].type)){
            var reader = new FileReader();
            reader.readAsDataURL(files[0]);
            reader.onloadend = function(){
                $(".preview-image").attr('src', this.result);
            }
        }
    });
});

When i create a new form group by clicking "Add new row" button, it can not preview the selected image. Any idea how I can fix this? Thanks.

1 Answers1

1

After adding new elements, we must have to bind change event to them as well. Try below code.

function imagePreview() {
    $(".userfile").unbind('change').bind("change", function() {
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return;

        if (/^image/.test( files[0].type)){
            var reader = new FileReader();
            reader.readAsDataURL(files[0]);
            reader.onloadend = function(){
            //Changed below line as well to show preview next to the changed element
                $(this).next(".preview-image").attr('src', this.result);
            }
        }
    });
}
$('#copy-btn').click(function(){
    newOne = $('#hide-ele').html();
    $('#form-group-wrapper').append(newOne);
    imagePreview();
});
$(function() {
    imagePreview();
});
Rupali
  • 1,068
  • 1
  • 12
  • 18