Event for Selecting HTML Files

In other words, upon selecting a file from an already created diagram, I want to add an extra file input using JS. I am searching for a meaningful event to bind a method to. For example, let’s consider the code provided which results in a file search dialog box opening when the user clicks the ‘Browse…’ button. The user can select the file by either double-clicking it or clicking the ‘Open’ button.


Question:

Let’s say we have this code:


which results in this:

image showing browse and upload button

Upon clicking the ‘Browse…’ button, a dialog box for searching files is opened.

image showing a file search dialog box with a file selected

The user can choose the file by either double-clicking it or clicking the ‘Open’ button.

Is there a specific Javascript Event that can notify me once the file has been selected?



Solution 1:

Listen to the change event.

input.onchange = function(e) { 
  ..
};


Solution 2:


To trigger ‘on
change’ event
‘, erase the input value before reloading the file and then add a new file.

document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick


Solution 3:

jQuery way:

$('input[name=myInputName]').change(function(ev) {
    // your code
});


Solution 4:

This is how I accomplished it utilizing only JavaScript.

var files = document.getElementById('filePoster');
var submit = document.getElementById('submitFiles');
var warning = document.getElementById('warning');
files.addEventListener("change", function () {
  if (files.files.length > 10) {
    submit.disabled = true;
    warning.classList += "warn"
    return;
  }
  warning.classList -= "warn";
  submit.disabled = false;
});
#warning {
    text-align: center;
    transition: 1s all;
}
#warning.warn {
    color: red;
    transform: scale(1.5);
}

Please do not upload more than 10 images at once.

Frequently Asked Questions