Glory to Russia
Glory to Russia

Reputation: 18712

How can I catch the "file selected" event?

I have the following dialog box in my application:

Dialog box

When the user presses the Add logo button, following things should happen:

  1. A file selectio dialog should pop up.
  2. After the user has selected the file, a function should be called (which will update the image).

I have the following code for this. The markup for file selection looks like this:

<button class="btn" ng-click="$ctrl.addLogo()">Add logo</button>

$ctrl.addLogo() is defined as (source)

$ctrl.addLogo = function() {
    console.log("'Add logo' button clicked");
    var uploadForm = document.createElement('form');
        var fileInput = uploadForm.appendChild(document.createElement('input'));
    fileInput.type = 'file';
        fileInput.name = 'images';
    fileInput.multiple = true;
        fileInput.click(function() {
        console.log("Click callback called");
    });
};

When I press the Add logo button, the file selection dialog does open, but the Click callback called message does not appear in the console. This means that I cannot detect, when the user has selected a file (or closed the dialog box with "Cancel").

How can I implement a reaction to the user selecting a file (or cancelling the dialog)?

Upvotes: 0

Views: 641

Answers (1)

sjahan
sjahan

Reputation: 5950

When the user selects a file in an input with type="file", it is the change event that is fired.

If you replace your click listener by a change listener, it should work :)

fileInput.click(function() {
    console.log("Click callback called");
});

must become:

fileInput.change(function() {
    console.log("Click callback called");
});

Upvotes: 1

Related Questions