Reputation: 3166
Please review my Fiddle...
I have a file upload button, which works fine. You'll see it when you barely scroll down in the fiddle. The image uploads, but it uploads down at the bottom of the page, and I'm trying to get it to display within a div, immediately below the upload button.
HTML...
`<input type='file' onchange="readURL(this);" /></label>
<p>
<strong>(Image will display below)</strong>
</p>
<div style="max-width: 100px; height: 100px; border:1px dashed black;">
<img id="blah" src="#" alt="Your image goes here..." />
</div>`
JS...
`$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});`
Upvotes: 1
Views: 4295
Reputation: 2225
Change the src attribute of the image you already have within the div. The following code should do what you want.
`$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var reader = new FileReader();
reader.onloadend = function() {
$('#blah').attr('src', reader.result);
}
reader.readAsDataURL(file); }
});`
Upvotes: 1
Reputation: 67
You're using after
which insert your image after the input
tag and not the image.
To insert your image inside your div
you need to have a selector on this div
like an id:
<input type='file' onchange="readURL(this);" /></label>
<p>
<strong>(Image will display below)</strong>
</p>
<div style="max-width: 100px; height: 100px; border:1px dashed black;" id="whatever">
</div>
And then do:
$('#whatever").html(img);
Upvotes: 1