Search code examples
javascriptjqueryjquery-pluginsuploadifyjavascript-framework

Check if they have selected a file?


I'm using the jQuery plugin, "uploadify" & what I'm trying to do is hide the upload button once the upload starts, however if they click it before selecting a file it still hides it anyway.

Here is my submit function:

$("#add_list").submit(function(){

    // Set new list id
    $("#filename").uploadifySettings('scriptData', { 'new_list_id': $('#new_list_id').val() });

    // Hide upload button
    $("#upload_button").hide();    

    // Trigger upload
    $("#filename").uploadifyUpload();

});

Is there a way I can get the value of the filename field? I've tried..

$("#filename").val()

..but that didn't work. Always blank even when selecting a file.


Solution

  • Ok..... So I decided to just update a hidden form field value with the 'onSelect' event; this way when they selected a file I can update the value to state they have selected a file; then check for this value before triggering the upload. If there is a problem with the upload or the user removes the file I updated the value to a blank value whenever the 'onCancel' event is triggered.

    Here is the relevant code if it helps anyone else..

        'onComplete': function(event, ID, fileObj, response, data) {
            if (response != 'OK') {
                // Cancel upload
                $("#filename").uploadifyCancel(ID);               
                // Show upload button
                $("#upload_button").show();          
                // Output error message
                alert(response); 
            } else {
                // Submit secondary form on page
                document.finalize.submit();
            }
        },
        'onError': function(event,ID,fileObj,errorObj) {
            // Cancel upload
            $("#filename").uploadifyCancel(ID);
            // Format error msg
            var error_msg = errorObj.type + '. Error: '  + errorObj.info + '. File: ' + fileObj.name;
            alert(error_msg);
        },
        'onSelect': function(event,ID,fileObj) {
            // Update selected so we know they have selected a file
            $("#selected").val('yes');
        },
        'onCancel': function(event,ID,fileObj,data) {
            // Update selected so we know they have no file selected
            $("#selected").val('');
        }
    });
    $("#add_list").submit(function(){
    
        var selected = $("#selected").val();
    
        if (selected == 'yes') {
    
            // Set new list id
            $("#filename").uploadifySettings('scriptData', { 'new_list_id': $('#new_list_id').val() });
    
            // Hide upload button
            $("#upload_button").hide();    
    
            // Trigger upload
            $("#filename").uploadifyUpload();
    
        } else {
    
            alert('Please select a file to upload.');
    
        }
    
    });