Reputation: 665
I'm trying to display a an image as it's uploaded.
I have the following code, which works fine for a single form input:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
<img width="50px" id="blah" src="#" alt="your image" />
However, I have multiple forms per page all with the same function in mind - each displaying an image once uploaded.
How can I make this work for multiple, dynamic forms?
Upvotes: 1
Views: 53
Reputation: 124
function readURL(input) {
var file = input.files[0];
if(file)
{
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
$(input).parents().find('img.blah').attr('src', e.target.result)
}
}
}
$("#imgInp").change(function(){
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img width="50px" class="blah" src="#" alt="your image" />
<input type="file" id="imgInp" name="img" />
</div>
Upvotes: 1