I generate procedurally a div containing an image and an input file in an HTML file.
The ID of all the element change by 1 each time. Here is the sample of the div that is repeated with K as the number that is incremented each time I generate this div, so every item has a different ID.
<div>
<img id="frame-add-K" src="" class="img-fluid" />
</div>
<label style="border: 2px solid black" for="img-input-K" class="btn">Select Image</label>
<input type="file" name="image_content_K" id="img-input-K" style="display:none; visibility:hidden;" accept="image/*" />
The div containing the image is supposed to work as a preview. So when the user input his image, I want to change the img source to the newly updated image.
I have tried something like this using jquery:
$(document).ready(function() {
$("input[id^=img-input-]").on("input", function() {
var id_input = $(this).attr('id').substring('img-input-'.length); //get me only the number at the end
$("#frame-add-" + id_input).attr("src", event.target.files[0]);
});
});
But id_input is always egual 1, so the change only affect my first div and change always the first image source. Moreover "event.target.files[0]" doesn't work there.
I ideally would like to make a generic function using jquery that would get the K of the element changed et update the image src associated with this K but I am open to any suggestion solving my issue.