tags:

views:

134

answers:

2

When uploading some image/audio/video files in the same batch I want the file selected in the one field should not get accepted in the other buttons. How can I achieve this?

A: 

sorry the question does not make much sense. Can you try to explain in more detail and maybe post some code or a link to your issue.

redsquare
+1  A: 

I think you are asking how to make it so no two files in a list of file upload boxes are the same, so you don't accidentally upload the same file twice.

This could be easily done using the input.onchange event. When you add a new file input box, assign its onchange event to a function like this one:

function fileChanged()
{
        $(createFileInput()).insertAfter(this).wrap('<p>' + '</p>').change(fileChanged);

        if(!isFileUnique(this))
        {
            $(this).remove();

            alert('You already chose to upload this file.\nPlease choose a different file.');

            return false;
        }

        return true;
}

Use some helper functions:

function isFileUnique(input) {
    if(input.value == '')
        return true;

    var fileInputs = $(input).parents('form').find('input:file');

    var sameInputs = $.grep(fileInputs, function(item, index) {
        if(item == input)
            return false;

        if(item.value == input.value)
            return true;

        return false;
    });

    return sameInputs.length == 0;
}

function createFileInput() {
    var input = document.createElement('input');

    input.type = 'file';

    return input;
}

Things are a little complicated because you can't do a mere "this.value = '';" So we just delete "this" and create a new input field. We need to create a new one anyway (so the user can upload an extra file), so it the issue is counteracted.

(Return values for fileChanged aren't needed, because I don't think file inputs will allow Javascript to ignore the change command.)

strager