How can I achieve loading the same files as a package using jQuery?

When loading some images / audio / video files in one batch, I want the file selected in one box not to be accepted in other buttons. How can I achieve this?

0


source to share


1 answer


I think you are asking how to make it so that the two files in the file upload field list do not match, so you don't accidentally upload the same file twice.

This can be easily done using the input.onchange event. When you add a new file input field, assign its onchange event to the following function:

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 tricky because you can't just do "this.value = '';" So we just remove "this" and create a new input field. In any case, we need to create a new one (so that the user can upload an additional file), so the problem is counteracted.

(The return values ​​for fileChanged are unnecessary because I don't think the input files will allow Javascript to ignore the change command.)

+1


source







All Articles