Search code examples
htmlinputpreventdefault

event.preventDefault() on file input doesn't seem to work


HTML

<input id="file-upload" name="files" type="file" multiple="">

JavaScript

if (inputType === "file") {
  console.log(event);
  event.preventDefault();
  console.log(event.target.files);

  /* do other stuff */
}

When I select a file, its name shows next to the input and also it is added to the FileList of the input, so what exactly is event.preventDefault() preventing? :/

animated gif showing input

Aim (eventually at least)

Allow users to select files, but stop default behaviour, grab the file(s) and append them to FormData manually and also (this is a nice to have) list the file(s) selected for upload by creating some HTML on the fly.


Solution

  • There is actually no default action for a input’s change event so calling preventDefault() on the event will have no effect.

    EDIT:

    The FileList object cannot be modified, so how do you modify a file collection?

    Well, the answer is pretty simple.

    1. Declare and initialize the custom FileList array

      var selectedFiles= [];

    2. In the onChange event, append the selected files to that variable:

      array.forEach(e.target.files, (file) => {
              selectedFiles.push(file);
         });
      
    3. Append the variable to FormData and submit

      let formData = new FormData(document.querySelector('#request-for-change-form'));
      
      // Creates a new request
      var request = new XMLHttpRequest();
      request.open("POST", "{your action here}");
      
      // Append the files to the formdata
      for (var i = 0; i < selectedFiles.length; i++) {
        formData.append("files[]", selectedFiles[i]);
      }
      
      // Submit the form
      request.send(formData);