I am creating a form in MVC and all the fields are dynamically generated. There are controls for multiple file upload. I want to show the total number of files uploaded for each control individually in a label/span which should also be dynamically generated using JQuery.

JQuery code:

$(".file-upload").on("change", function () {
            debugger;
            var files = $(this)[0].files;
            var count = files.length;
            if (count != 0) {
                $(".file-upload").append('<span class="file-upload-count success">' + count + '"files successfully uploaded"</span>');

            } else {
                $(".file-upload").append('<span class="file-upload-count failure">"Upload files again."</span>');

            }
        });

form.cshtml:

<td>   
    <span class="fa fa-plus" onclick="document.getElementById('@l_UploadID').click(); ShowFileCountLabel('@l_UploadID','')"></span>
    @Html.TextBoxFor(model => model.ExpenseDetails[i].files, "", new { @id = @l_UploadID, @type = "file", @multiple = "multiple", @class = "invisible file-upload", @style = "height:0px" })
</td>

1 Answers

0
iArcadia On Best Solutions

Your <span.file-upload-count> is not appended into your DOM tree because you are trying to append it into an <input> element, which is not possible. You need to add it into an element that can have children, like a <div>.

About chosen file names, there are available with the items of the this.files object (or $(this)[0].files if you absolutly want to use jQuery).

const jUploadLabel = $('div').first(),
  uploadInput = document.getElementById('@l_UploadID'),
  jUploadCount = $('#file-upload-count');

// Opens the file navigator when the label is clicked.
jUploadLabel.on('click', () => {
  $(uploadInput).click();
});

$(uploadInput).on("change", function () {
  let files = this.files,
    count = files.length,
    fileWord = (count > 1) ? 'files' : 'file';
    
  // Removes counter element's content and classes.
  jUploadCount.empty().removeClass('sucess failure');

  // If at least one file chosen...
  if (count > 0) {
    jUploadCount.addClass('success');
  
    jUploadCount.append(
      `<div>${count} ${fileWord} successfully uploaded.</div>`
    );

    // For each chosen file, displays its filename.
    for (let file of files) {
      jUploadCount.append(
        `<div>${file.name}</div>`
      );
    }
  }
  // ...else if no file...
  else {
    jUploadCount.addClass('failure');
  
    jUploadCount.append(
      '<div>Upload files again.</div>'
    );
  }
});
.invisible {
  display: none;
}

.success {
  color: green;
}

.failure {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fa fa-plus">Choose a file</div>
<input class="invisible file-upload" id="@l_UploadID" type="file" multiple>
<div id="file-upload-count"></div>