Search code examples
javascriptjqueryjquery-file-upload

jQuery trigger only occurs first time


Clicking #input multiple times will upload a file each time.

Clicking #button which in turn triggers #input will only upload a file the first time (and not at all if #input was first clicked). I will, however, open the file selector browser, just not upload the file.

Why is this, and how do I change it to allow it to be clicked multiple times?

PS. Why I wish to do so instead of just using an #input? I am using jQueryUI Dialog and wish one of the buttons to initiate the input.

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My profile</title>
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui.min.js"></script>
        <script type="text/javascript" src="js/jquery.fileupload.js"></script>
        <script type="text/javascript"> 
            $(function(){
                $('#button').click(function(){uploader.trigger('click');});
                var uploader=$('#input').fileupload( {
                    url: 'upload.php',
                    formData: {user_id:50},
                    dataType: 'json',
                    }
                );
            });
        </script>
    </head>
    <body>
        <button id="button">Click</button>
        <input id="input" type="file" name="name">
    </body>
</html>

Solution

  • As far as I think, there should be a change in the order where you first initialize the variable uploader and where you register the click event on the #button.

    Update

    Meanwhile, initiating the uploader variable upon clicking #button each time should solve the problem:

    $(function(){
                $('#button').click(function(){
                    var uploader=$('#input').fileupload( {
                    url: 'upload.php',
                    formData: {user_id:50},
                    dataType: 'json',
                    });
                    uploader.trigger('click');
                 });
            });