Multiple Image Upload with Preview
by douglasloyo
HTML
<input id="addButton" type="button" value="(+)">
<ul id="imgArray"></ul>
CSS
img {
border:2px solid gray;
border-radius: 50%;
width:150px;
height:150px;
}
JavaScript
var index=0;
function addImgCtrl(){
index++;
$("#imgArray").append(createTemplate(index));
}
function createTemplate(fileId){
var li = $('<li />');
var fileInput = $('<input />', {
type : 'file',
value : 'Image',
id : 'file'+fileId,
on : {
change: function() {
previewImage(this);
}
}
});
var previewImg = $('<img />', { id: 'previewfile'+ fileId});
li.append(fileInput).append(previewImg);
return li;
}
function previewImage(input) {
if (input.files && input.files[0]) {
var inputId = $(input).attr("id");
var reader = new FileReader();
reader.onload = function (e) {
$('#preview'+inputId)
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
// On Ready
$(function(){
// Add event hadler to the main button.
$("#addButton").on("click",addImgCtrl);
});