Issue
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>
Solution
You dont need any if condition. One way to do this like this. jsfiddle here
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(input).closest('div').siblings('.imgDiv').find('img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInput, #emzaInput").change(function(){
readURL(this);
});
Other approach is by adding another parameter in function that will pass img element id. see here
function readURL(input, imgID) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#' + imgID).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInput").change(function(){
readURL(this, 'person');
});
$("#emzaInput").change(function(){
readURL(this, 'emza');
});
Answered By - mustafa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.