Reputation: 1167
I hide input type and show only image which is used to choose file and on change of input I call a function :
function showpreview(file) {
var previewImg = $(file).parent().find('img').eq(0);
if (file.files && file.files[0]) {
console.log(window.URL.createObjectURL(file.files[0]));
previewImg.src = window.URL.createObjectURL(file.files[0]);
} else {
previewImg.src = "blankpreview.png";
}
console.log(previewImg.src);
console.log(previewImg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<label for="exampleFormControlFile2">
<img style="height:170px;" class="img-thumbnail" src="blankpreview.png" />
</label>
<input type="file" onchange="showpreview(this)" name="Screen_2" accept="image/jpeg, image/png" class="form-control-file d-none" id="exampleFormControlFile2" required />
</div>
This show correct source and element in console but image doesn't change
Upvotes: 1
Views: 67
Reputation: 250922
Because you want to work with the raw DOM element, you need to grab that in your selector...
var previewImg = $(file).parent().find('.img-thumbnail').eq(0)[0];
Note the additional [0]
at the end. Let's deal with it in steps below...
$(file).parent()
.find('.img-thumbnail') // find the thumbnail image
.eq(0) // "I only want the first one you find"
[0]; // Give me the DOM element that's inside the jQuery object
function showpreview(file) {
var previewImg = $(file).parent().find('.img-thumbnail').eq(0)[0];
if (file.files && file.files[0]) {
previewImg.src = window.URL.createObjectURL(file.files[0]);
} else {
previewImg.src = "blankpreview.png";
}
console.log(previewImg.src);
console.log(previewImg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<label for="exampleFormControlFile2">
<img style="height:170px;" class="img-thumbnail" src="blankpreview.png" />
</label>
<input type="file" onchange="showpreview(this)" name="Screen_2" accept="image/jpeg, image/png" class="form-control-file d-none" id="exampleFormControlFile2" required />
</div>
Upvotes: 3
Reputation: 28522
You can use .attr('src',yourimage)
to set src of your image tag.
Demo Code :
function showpreview(file) {
var previewImg = $(file).parent().find('img') //no need of eq..
if (file.files && file.files[0]) {
console.log(window.URL.createObjectURL(file.files[0]));
previewImg.attr('src', window.URL.createObjectURL(file.files[0])); //use .attr here
} else {
previewImg.attr('src', "blankpreview.png");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<label for="exampleFormControlFile2">
<img style="height:170px;" class="img-thumbnail" src="blankpreview.png" />
</label>
<input type="file" onchange="showpreview(this)" name="Screen_2" accept="image/jpeg, image/png" class="form-control-file d-none" id="exampleFormControlFile2" required />
</div>
Upvotes: 4