I am trying to allow multiple file uploads before a form post. I would like the user to only see one file upload item, and every time a file is selected, show a new <li>one that contains the file name and image / link to remove this particular file from the collection. There's a jQuery MultiFile plugin that does what I want, but I can't get the custom style to work the way I want, so I ride on my own.
So far I have the code below. It successfully adds <li>, hides the file upload element with the newly selected file, and adds an empty file upload element to the page so that the user can select a new file. I try my best to manage the removal of elements, and although it is not so difficult, I looked at it for a long time, and now it seems to me that I'm doing everything wrong. I hope others can have some understanding, tips for cleaning it (i.e. make it more elegant) and the like. The code is below.
HTML:
<div id="product-image-area" class="group" style="border-bottom: none; padding-top: 0">
<ul id="photos" class="nobull">
<li id="no-product-images-msg" class="" >
<%= Html.Image("no-photos.png") %>
</li>
</ul>
</div>
<div id="upload-area">
<h4 class="st">Upload an image</h4>
<p class="note">Allowed file types are .gif, .jpg, .jpeg, and .png</p>
<p id="file-input" class="st sb"><input class="photo-upload" id="VenuePhotos_0" name="VenuePhotos[]" type="file" /></p>
</div>
Script:
$(function () {
$('.photo-upload').live('change', function () {
var fileCount = new Number($(this).parent().children('.photo-upload').length);
$('#photos').append('<li id="venue_photo_' + (fileCount - 1) + '">' + $(this).val() + '<img title="' + (fileCount - 1) + '" src="/vh/public/images/icon-delete.png" class="delete" /></li>');
$(this).parent().append(
$(this).clone().attr('id', 'VenuePhotos_' + fileCount)
);
$(this).hide();
});
$('.delete').live('click', function (e) {
var index = $(e).attr('title');
$('#file-input').children('.photo-upload').remove('#VenuePhotos_' + index);
$('#photos').children().remove('#venue_photo_' + index);
});
});
source
share