bulk upload with the ability to remove files

I'm in the process of creating a multiple file upload with delete option, similar to the design shown in this image:

https://i.sstatic.net/RomOR.jpg

I have been following an example on this JS Fiddle demo. My goal is to eliminate the button with the id attribute uploadBtn and instead utilize the native browser file input for uploading.

Here is the code I have so far:

HTML

<input type="file" id="uploadFile" name="FileUpload"  multiple="multiple"/>
<div id="upload_prev"></div>

JavaScript

$(document).on('click','.close',function(){
    $(this).parents('span').remove();

})

$('#uploadFile').on('change', function() {

    var filename = this.value;
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    var files = $('#uploadBtn')[0].files;
    for (var i = 0; i < files.length; i++) {
     $("#upload_prev").append('<span>'+'<div class="filenameupload">'+files[i].name+'</div>'+'<p class="close" >X</p></span>');
    }    
}

CSS

.filenameupload {
    width:98%;  
}

#upload_prev {
    border:thin solid #000;
    width: 65%;
    padding:0.5em 1em 1.5em 1em;
}

#upload_prev span {
    display: flex;
    padding: 0 5px;
    font-size:12px;
}

However, the current setup doesn't display the file names with the remove feature. What adjustments should I make here?

Answer №1

Attempting to assign a value to an input type="file" is incorrect and will result in errors.

It is recommended to use an input type="text instead and experiment with that element.

Answer №2

There are a couple of modifications to consider:

  1. Ensure that the DOM is fully loaded using .ready() before attaching event handlers.

    $(document).ready(function(readyEvent) {
        //initialize observers
    
  2. Include the change event argument in the change handler, and utilize event.target.files instead of $('#uploadBtn')[0].files;. For more information, visit the passing data section on.on().

    $('#uploadFile').on('change', function(changeEvent) {
         var files = changeEvent.target.files;
    

Check out the changes in action at this updated plunker.

Update:

In your inquiries about removing an item from the list ("once I am eliminating the files individually, the initial count of selected files does not update, do you have any suggestions on how to show the remaining number when removing files?")

Refer to this response:

"If you wish to delete specific selected files: it is not possible. The File API Working Draft you referenced includes a note:"

The HTMLInputElement interface [HTML5] has a readonly FileList attribute, […] [emphasis mine]

Therefore, you can clear the entire list but not individual items within it.

$(document).on('click', '.close', function(closeEvent) {
    $(this).parents('span').remove();
    var fileInput = $('#uploadFile')[0];

    //clear all selected files from the file input field
    fileInput.value = '';
}

Another approach could be to commence uploading files during the change event, and after each upload completion, insert a hidden input with the uploaded file's ID that can be deleted upon clicking the remove button.

Answer №3

Give this a shot

<div class="row uploadwrapper">
<div class="col-md-6">
<input type="file" class="image-upload" name="image[]" accept="image/jpeg">
</div>
<div class="col-md-6">  
<button type="button" onclick="addUploadField(this)">+ Add another image</button>
</div>
</div>

function addUploadField(element)
{
var image = $(element).parent().prev().find('input[type="file"]').val();
if(image != '')
{
var cloneWrapper = $(element).parent().parent().clone();                
cloneWrapper.find('button').removeAttr('onclick');
cloneWrapper.find('button').attr('onclick','removeUploadField(this)');
cloneWrapper.find('button').html('- Remove image');
$(element).parent().parent().before(cloneWrapper);
$(element).parent().prev().find('input[type="file"]').val('');
}
}

function removeUploadField(element)
{
$(element).parent().parent().remove();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

retrieving request headers using XMLHttpRequest

Is there a way for me to access my requestHeaders within the onload function? Any guidance on how to achieve this would be greatly appreciated. Many thanks! ...

Stop underscore templates from accessing global variables

I have a question about my underscore template. Here is the section of code in question: <% if (typeof title !== "undefined") { %> <p class="title"><%= title %></p> <% } %> Is there a way to avoid using the global scope ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

End the response after sending with res.send() within the module

I am in the process of developing a module for validating requests that come through req.body. Instead of repeating the same code snippet in every server request, I aim to consolidate it into a single line within a module. const errors = validationResult( ...

What is the best way to obtain the current time in a specific city?

Is there a simpler way to display the current time for a specific location without having to deal with factors like daylight savings time? I am searching for a more straightforward solution to always show the time for a particular city, zip code, or any o ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Automatically preselect the checkbox inputs with the API and update their status when they are interacted with

Hello fellow developer, I trust you are doing well. I am looking to have the checkboxes automatically checked based on data from the API and update their status when interacted with. I've tried different approaches but haven't found the right sol ...

Customizing DataTables row data with JSON inputs

Upon receiving JSON data on my website, it includes an array, an array of objects, and a string. For example: data = { labels: ['a', 'b', 'c', 'd', 'e',] , staff: [ {'name' : 'aaa', &a ...

How to set a cookie within an iframe while using Safari browser

Despite searching extensively on Stackoverflow and various other sources, I have not been able to find a solution that works for my specific case. The scenario is as follows: we have an application on domain A that we do not have control over, and an appl ...

Incorporating the use of font color in CSS styles and

I am creating a newsletter template using foundation. Within the table, there are 2 <th> elements containing the content "Reservationnumber" and "23425-FF3234". I have multiple instances of these <th>. I want to apply a colored font to them. Wh ...

Reformat an input number by substituting commas with periods

Here's the code I'm working with: <input type="number" tabindex="3" placeholder="Item Price" step="0.01" min="0.10" max="999.99"> An example value inside this input is 1,95. I need to replace the comma with a dot. Can this be done using ...

Unexpected behavior with Ember.js Ajax request

I recently started using the Ember.js framework. While attempting to make an AJAX call from the framework, I encountered unexpected results. Below is the code snippet on the page - Link to the first AJAX call, which is functioning as intended. {{#linkT ...

What is the best way to retrieve a specific value from a JSON file using a numerical identifier?

Imagine a scenario where there is a JSON file structured like this: { "data": [ { "id": "1", "name": "name1" }, { "id": "2", "name": "name2" } ] } If you know the ...

Navigate to homepage using ajax

As I delve into using ajax, I seem to have hit a roadblock. Despite my best efforts, I haven't been able to find a solution to my issue. I'm puzzled as to why the page doesn't redirect to the index after the request is sent: Here is the co ...

The ng-if directive seems to be causing issues within an ng-repeat loop when used in conjunction with bind-html

Below is the code I am using to bind html in my webpage: <div bind-html-compile="menuButtonView"></div> This is the code in my controller: dashboardService.getTemplateMetaData(data.templateCategory) .success(function(data) { console.lo ...

Lag in jQuery Animate Property

Hello fellow developers! I am currently working on a promotional website where both the homepage and subpages are contained within the same index file. The transition between the content occurs when users click on the menu items. There are a total of 4 su ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

What is the best way to fetch d3 data from a service?

I've been exploring a tutorial on creating charts with d3, which can be found at: When it comes to loading data for use in d3, I typically rely on the following code snippet: d3.tsv("data.tsv", type, function(error, data) { The file "data.tsv" is c ...