Question

I'm using the jQuery File Upload plugin. I'm hiding the file input and activating it upon clicking a separate button. (See this fiddle.)

HTML:

<div>
    <button class="browse">Browse</button>
    <input id="upload" type="file" style="display: none;" />
</div>

JavaScript:

var element = $("#upload");

$(".browse").click(function () {
    $("#upload").trigger("click");
});

element.fileupload({
    add: function () {
        alert("add");
    }
});

Notice that if you press the button then select a file, the add method is activated and you'll get an alert. Do it again, and you'll get another alert.

Now, see this fiddle. The only difference is that I've changed the following line

$("#upload").trigger("click");

to

element.trigger("click");

Notice that now, the first time you click the button then select a file, the add method is activated and you get the alert (just like before), but if you do it again, the add method never activates.

What is causing this difference in behavior?

Was it helpful?

Solution 2

It looks as though the scope of element is being lost / changed after the add function. Resetting it like below seems to work.

var element = $("#upload");

$(".browse").click(function () {
    element.trigger("click");
});

element.fileupload({
    add: function () {
        alert("add");
        element = $(this);
    }
});

Fiddle

OTHER TIPS

This can also be solved by setting replaceFileInput to false, as stated by the documentation. This is because the plugin recreates the input element after each upload, and so events bound to the original input will be lost.

Try this one: http://jsfiddle.net/xSAQN/6/

var input = $("#upload");

$(".browse").click(function () {
    input.trigger("click", uploadit(input));
});

function uploadit(input){
    $(input).fileupload({
        add: function () {
            alert("add");
        }
    });
}

Although there is one more way:

just change to this:

   var element = $("#upload");

   $(".browse").click(function () {
       $("#upload").click(); // <----trigger the click this way
   });

   element.fileupload({
      add: function () {
          alert("add");
      }
   });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top