0

In my html page I create dynamically file input fields. For automatically upload the files I use on change event and ajax.

<input type="file" id="upload" multiple="multiple" />

$(function() {

    $(document).on('click', '#upload', function() {

        $(this).on('change', function() {
            //upload file via ajax
            alert('upload files');
        });
    });

});

This works fine but I have a problem when you cancelled the file selection and then you rerun the selection of files to upload. The files are uloaded more times.
How can I fix this problem? Thanks

Gus
  • 913
  • 2
  • 15
  • 30

1 Answers1

0

Why your files are uploaded more times. because in every click you are binding your event so see this example.

1) click on Choose file and select any file it will show upload files alert 1 time.

2) now agin click on Choose file now it will alert 2 time and so on...

3) now agin click on Choose file and dont select file click on cancel then again it will bind event and call you ajax function.

So event if you cancel then also it will trigger event. which is bind earlier in click.

.on delegate event

Problem Explanation


 $(document).on('click', '#upload', function() {

        $(this).on('change', function() {
            //upload file via ajax
            alert('upload files');
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="upload" multiple="multiple" />

Example 1 Working


 $('#upload').on('change', function() {
            //upload file via ajax
            alert('upload files');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="file" id="upload" multiple="multiple" />
Keval Bhatt
  • 6,224
  • 2
  • 24
  • 40