Tim Wiel Tim Wiel - 2 months ago 7
jQuery Question

Referencing jQuery element between fileupload plugin methods

I need to be able to reference a created jQuery Element in both the add method and done method of the jQuery file upload plugin. It is created in the add method but needs to be replaced in the done method

Currently during multiple uploads the theFilemanagerRow is overwritten each time by the next iteration of the next file

Question is: how do I access the unique theFilemanagerRow from the "add" function in the "done" function for each unqiue file uploaded when multiple files are uploaded.

Single files work however it seems that for multiple file selections the add function is run for each of the multiple files so it overwrites the theFilemanagerRow and the done function only receives the theFilemanagerRow that is set by the "add" function at the time that "done" completes - hope that makes sense!!

frameContainer.find('INPUT[type=file]').each(function() {
var file_field = $( this );
var theFilemanagerRow = false;

file_field.fileupload({
dataType: 'json',
formData: formData,
add: function(e, data) {
//need reference to element here
theFilemanagerRow = $('<tr>', {
id: Math.random().toString(36).substr(2, 10)
});
},
done: function(e, data) {
if (theFilemanagerRow.length == 1) {
theFilemanagerRow.replaceWith(anotherElement);
}
}
});

});


I have simplied the code for clarity here so the elements are used in the document, anotherElement is created elsewhere, etc.

Answer

You could use data.context

  add: function(e, data) {
    // need reference to element here
    var theFilemanagerRow = $("<tr>", {
      id: /* set id */
    });

    data.context = theFilemanagerRow;
  },
  done: function(e, data) {
    // get `.data()` of current element
    var tr = data.context;
    if (tr.length == 1) {
      tr.replaceWith(anotherElement);
    }
  }
Comments