xaero
xaero

Reputation: 99

Fire javascript event onchange event of <input type="file"/>

I have this code

<input id="fileupload" 
       type="file" name="files[]" 
       class="inputFile clickable" 
       onchange="uploadFile(this.value)"/>

This works fine on second time using it, i.e. first time I select the file the onchange event does not fire, but selecting file for the second time works fine.

Is there any thing which I can change here?

I have tried:

Additional info: If I use onchange=alert(this.value) it works fine

this is my javascript code

function uploadFile(value) {
     alert(value); //works fine
    $('#fileupload').fileupload({
        dataType: 'json',
        url: 'fileUpload.php',
        type: 'POST',
        limitConcurrentUploads: 1,
//        done: function (e, data) {
//            $.each(data.result, function (index, file) {
//                $('<p/>').text(file.name).appendTo(document.body);
//            });
//        },
        success: function() {
            showMultipleDataDiv(value); //but I don't get value here
        }
    });
}

Upvotes: 2

Views: 12049

Answers (1)

Rodrigo5244
Rodrigo5244

Reputation: 5535

The code $('#fileupload').fileupload will trigger a file upload as soon as the user selects a file. You need to run this code before the user selects a file, because it adds an event listener to the input tag. Since you only run this code after the user selects a file, then it will only work on the second time.

This is the change you need to do to make it work

$(function () {
  $('#fileupload').fileupload({
    dataType: 'json',
    url: 'fileUpload.php',
    type: 'POST',
    limitConcurrentUploads: 1,
    //        done: function (e, data) {
    //            $.each(data.result, function (index, file) {
    //                $('<p/>').text(file.name).appendTo(document.body);
    //            });
    //        },
    success: function () {
      showMultipleDataDiv(value); //but I don't get value here
    }
  });
});

Notice there is no need to add code in the change event. The plugin is going to do that for you.

You can read more about it here: https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

Upvotes: 1

Related Questions