AnApprentice
AnApprentice

Reputation: 111080

jQuery, how to check if a plugin has already been applied to a div?

jQuery File Uploader: https://github.com/blueimp/jQuery-File-Upload

I'm using the plugin above. How in jQuery can I check to see if the fileUpload has already been applied?

I get the following error now:

Uncaught FileUpload with namespace "file_upload" already assigned to this element
jQuery.jQuery.extend._Deferred.deferred.resolveWithjquery-1.5.1.js:869
donejquery-1.5.1.js:6591
jQuery.ajaxTransport.send.callbackjquery-1.5.1.js:7382

Is there a way to check before my function calls:

$('.upload').fileUploadUI({
 .........
 .........
 .........

Thanks

Upvotes: 7

Views: 9482

Answers (3)

Tomasz
Tomasz

Reputation: 96

You can also do this

if(undefined != $('.upload').data('blueimp-fileupload') ){
    console.log( 'plugin already applied to the element' );
}
else console.log( 'plugin not applied to the element' );

Upvotes: 2

Sebastian Tschan
Sebastian Tschan

Reputation: 1444

The jQuery File Upload plugin stores a reference to it's FileUpload handler as jQuery data object.
The error message "FileUpload with namespace "file_upload" already assigned to this element" comes from the plugin's own check for this data reference.

You can initialize the plugin the following way to prevent this error:

$('.upload').not(function () { return $(this).data('file_upload'); }).fileUploadUI({/*...*/});

Upvotes: 2

Dutchie432
Dutchie432

Reputation: 29170

You can add/set a class as a flag of sorts. In this case, we'll add a class called applied

//scroll through each upload item
$('.upload').each(function(){

    //Make sure class is not found
    if (!$(this).hasClass('applied')) 

        //Apply Class and Upload Plugin
        $(this).addClass('applied').fileUploadUI({...}); 
}); 

Update as pointed out below by yoavmatchulsky, you could also, more easily do

$('.upload:not(.applied)').addClass('applied').fileUploadUI({...});

Upvotes: 17

Related Questions