Image Preview Not Showing After Cloning Html Form Tag
I have created a nested comment system using html, jQuery, Ajax, and Javascript. For each reply button, I have created the same input features as the original message, which inc
Solution 1:
$(document).ready(function() {
var cloneCount = 0;
var bindFileChange = function (cloneCount){
let fileInput = $('input[type="file"][data-count="' + cloneCount +'"]');
fileInput.on('change', function (){
$(this).siblings('.image_Preview').attr('src', window.URL.createObjectURL(this.files[0]));
});
};
$("button").click(function(){
cloneCount++;
$("#id0").clone().attr('id', 'id'+ cloneCount).insertAfter("#id" + (cloneCount - 1));
$('#id' + cloneCount).find('input[type="file"]').first().attr('data-count', cloneCount);
bindFileChange(cloneCount);
});
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><formid="id0"method="post"enctype="multipart/form-data"data-count="0"><div><imgclass="image_Preview"width="100"height="100" /><inputtype="file"class="fileUpload"data-count="0"></div><div><inputtype="submit"name="submit"id="submit"class="btn btn-info"value="Submit" /></div></form><buttonid="click">Reply</button>
I'll update this answer after seeing your js bin. It's updating the image preview because you have an id assigned to it. Id's should be unique. So first off I would remove the id attribute from your img
elements and also remove the change
event on your file input, we can bind it dynamically with js later. In order to target the elements with js though we're going to need to keep a count of the replies, data attributes
are handy for this.
<formid="id0"method="post"enctype="multipart/form-data"data-count="0"><div><imgclass="image_Preview"width="100"height="100" /><inputtype="file"class="fileUpload"data-count="0"></div><div><inputtype="submit"name="submit"id="submit"class="btn btn-info"value="Submit" /></div></form><buttonid="click">Reply</button>
Now for the js, you're on the right track incrementing the form's id. We need to apply this to other elements too so we can target them.
$(document).ready(function() {
var cloneCount = 0;
var bindFileChange = function (cloneCount){
let fileInput = $('input[type="file"][data-count="' + cloneCount +'"]');
fileInput.on('change', function (){
$(this).siblings('.image_Preview').attr('src', window.URL.createObjectURL(this.files[0]));
});
};
$("button").click(function(){
cloneCount++;
$("#id0").clone().attr('id', 'id'+ cloneCount).insertAfter("#id" + (cloneCount - 1));
$('#id' + cloneCount).find('input[type="file"]').first().attr('data-count', cloneCount);
bindFileChange(cloneCount);
});
});
Post a Comment for "Image Preview Not Showing After Cloning Html Form Tag"