I'm trying to create a form where I can have multiple file upload sections, where the user can upload multiple files.
That part, is reasonably straight forward. My problem comes from allowing the user to 'remove' a file from the upload list, before it's uploaded.
I've created a fiddle to illustrate
http://jsfiddle.net/alexjamesbrown/o62srbew/
I've got a simple row, that holds the <input type="file"
<div class="row files" id="files1">
<h2>Files 1</h2>
<span class="btn btn-default btn-file">
Browse <input type="file" name="files1" multiple />
</span>
<br />
<ul class="fileList"></ul>
</div>
then, so far, I've created a jquery plugin so it's re-usable:
$.fn.fileUploader = function (filesToUpload) {
this.closest(".files").change(function (evt) {
for (var i = 0; i < evt.target.files.length; i++) {
filesToUpload.push(evt.target.files[i]);
};
var output = [];
for (var i = 0, f; f = evt.target.files[i]; i++) {
var removeLink = "<a href=\"#\" data-fileid=\"" + i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name), "</strong> - ",
f.size, " bytes. ", removeLink, "</li> ");
}
$(this).children(".fileList")
.append(output.join(""));
});
};
I'm then initialising my very basic plugin like this:
var filesToUpload = [];
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function (e) {
e.preventDefault();
});
As in this JSFiddle, I've added a class name .removeFile
to the dynamically generated remove
link; then use this class as a selector to pick up the one which is clicked and remove the parent li
.
Updated:
JS:
// add .removeFile class to the li's element to pick them by this selector
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name), "</strong> - ",
f.size, " bytes. ", removeLink, "</li> ");
}
$(this).children(".fileList")
.append(output.join(""));
});
};
var filesToUpload = [];
$(document).on("click",".removeFile", function(e){
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for(i = 0; i < filesToUpload.length; ++ i){
if(filesToUpload[i].name == fileName){
//console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
//console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
You can un-comment the console.log() statements to see the result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With