Sweetie
Sweetie

Reputation: 1368

Creating multiple file upload logic

I am trying to create multiple file upload in an MVC Application. I am able to add a new div on the click of "Add" anchor tag. but I am only able to click the event of parent acnhor tag but not of the ones that I am creating with the below java script function.

  View Page
     <div id="ParentFileUploadDiv" style="width: 100%; float: left; padding: 5px 0;">
                                <div style="width: 100%; float: left;" id="FileBlock_1">
                                    <label>Find File</label>
                                    <input type="file" id="DocFile" name="DocumentFile" style="width: 45%; height: 25px;" />
                                    <a class="AddFile">
                                        <img src="~/Images/AddMore.png" />Add</a>
                                    <a class="RemoveFile">
                                        <img src="~/Images/Cross.png" />Remove</a>
                                    <div id="FileNM"></div>
                                    @*    <a class="DownloadImage" style="display: none !important;" title="Download File" id="DI_Anch" onclick="DownloadFile();"></a>*@
                                </div>
                            </div>

    <script>
    $('.AddFile').click(function () {

            var LastChildElement = $("#ParentFileUploadDiv").children().last();
            var GetLastNumber = LastChildElement.attr('id').split('_');
            var FileCounter = parseInt(GetLastNumber[1]) + parseInt(1);
            var curDiv = $('#ParentFileUploadDiv');

            var newDiv = '<div id="FileBlock_' + FileCounter + '" style="width: 100%; float: left;" >' +
                         '<label>Find File</label>' +
                         '<input type="file" name="DocumentFile" style="width: 45%; height: 25px;" />' +
                         '<a class="AddFile">' +
                         '<img src="/Images/AddMore.png" />Add</a>' +
                         '<a class="RemoveFile">' +
                         '<img src="/Images/Cross.png" />Remove</a>'
                         + '</div>';
            $(newDiv).appendTo(curDiv);

        });

        function RemoveFileUpload(div) {
            document.getElementById("FileUploadContainer").removeChild(div.parentNode);
        }
    </script>

Upvotes: 0

Views: 157

Answers (2)

A. Wolff
A. Wolff

Reputation: 74410

Delegate event to closest static parent:

$('#ParentFileUploadDiv').on('click','.AddFile', function(){...});

Upvotes: 1

JF it
JF it

Reputation: 2403

This is fairly hard to do.. have you considered using a plugin?

This one is free + easy to implement:

http://www.uploadify.com/demos/

(it is flash based.. a quick google search will allow you to find ones that are jquery/mvc based but having used this myself i can vouch for it.)

Upvotes: 0

Related Questions