I have 6 image upload's on my page and a script that will update the image preview when a new image is chosen. I don't want to have 6 scripts with just a changed id per script, so I was wondering how I would accomplish this as a javascript noob.
Each image upload has the id of logo-id-#
.
Bootstrap Image Upload:
<div class="col-md-2">
<div class="form-group">
<div class="main-img-preview center">
<img class="thumbnail img-preview" src="http://farm4.static.flickr.com/3316/3546531954_eef60a3d37.jpg" title="Preview Logo">
</div>
<div class="input-group">
<input id="fakeUploadLogo" class="form-control fake-shadow" placeholder="Choose File" disabled="disabled">
<div class="input-group-btn">
<div class="fileUpload btn btn-primary fake-shadow"><span><i class="glyphicon glyphicon-upload"></i> Browse</span>
<input id="logo-id-1" name="logo" type="file" class="attachment_upload">
</div>
</div>
</div>
</div>
Javascript:
<script>
$(document).ready(function() {
var brand = document.getElementById('logo-id-1');
brand.className = 'attachment_upload';
brand.onchange = function() {
document.getElementById('fakeUploadLogo').value = this.value.substring(12);
};
// Source: http://stackoverflow.com/a/4459419/6396981
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('.img-preview').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$("#logo-id-1").change(function() {
readURL(this);
});
});