Reputation: 5
Im trying to change the style of my default file upload to a preview based on. On change of a input field I want to update the src of the preview image. Thats working but just for the first type of file input. I want to be flexible if i want to add a upload input. Can you help me to find my faulty thinking?
HTML
<div class="file-uploader">
<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-1" style="display:none;" />
<img class="preview-1" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>
<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-2" style="display:none;" />
<img class="preview-2" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>
</div>
Script
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.file-uploader .preview-'+num_id).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
var num_id = $(".file-uploader input[type='file']").attr('class').match(/\d+/);
$(".file-uploader .upload-field-"+num_id).change(function(){
readURL(this);
});
Upvotes: 0
Views: 3095
Reputation: 616
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var num = $(input).attr('class').split('-')[2];
$('.file-uploader .preview-'+num).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("[class^=upload-field-]").change(function(){
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file-uploader">
<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-1" style="display:none;" />
<img class="preview-1" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>
<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-2" style="display:none;" />
<img class="preview-2" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>
</div>
Please check the code might help you out
Thanks
Upvotes: 2