I have two input element for personal image and signature image and two image element for display images
At the moment by selecting a image, both image element display the same picture,
How can each box display the image related to its input, or in other words, how can I bet on the id to display the corresponding image?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
// place of if condition base of element id for uploading related image
$('#person').attr('src', e.target.result);
$('#emza').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInput").change(function() {
readURL(this);
});
$("#emzaInput").change(function() {
readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="col-4">
<div class="col-auto p-1 col-3">
<label class="col-form-labels">personal image</label>
</div>
<div class="col-auto p-1 col-5">
<input class="myform-control" type="file" id="imgInput">
</div>
<div class="col-auto p-1 col-4">
<img id="person" src="..." class="img-thumbnail float-end rounded" alt="...">
</div>
<div class="col-4" style="display: flex; flex-direction: row;">
<div class="col-auto p-2">
<label class="col-form-labels">signiture image</label>
</div>
<div class="col-auto p-2">
<input class="myform-control" type="file" id="emzaInput">
</div>
<div class="col-auto p-2">
<img id="emza" src="..." class="img-thumbnail float-end rounded" alt="...">
</div>
</div>
</div>
2
Answers
If you applied a reference to the
img
element, using adataset
attribute, on theinput
element then a simple delegated listener could inspect theevent.target
and easily deduce to which HTML element the results of the image selection should be applied. That keeps the Javascript free from hardcoded ID attributes and means it could be scaled to any number of input/img pairsYou dont need any if condition.
One way to do this like this. jsfiddle here
Other approach is by adding another parameter in function that will pass img element id. see here