Search code examples
javascriptjqueryinput-type-file

how to get the files from multiple input file control?


I have multiple file input controls which are dynamically generated through code. I tried to put sample script which is as below

<input type="file id="file1" />
<input type="file" id="file2" />

JS:

    $(document).ready(function(){
        $('input:file').on('change', function ()
        {
            for (var i = 0; i < this.files.length; i++)
            {
                alert(this.files[i].name);
            }
        });
    });

I think my code is in getting the files is wrong.


Solution

  • I think you can do something like this:

    $('input[type="file"]').on('change', function() {
        $('input[type="file"]').each(function() {
            alert($(this).val());
        });
    });
    

    If I understood your question correctly this should do what you need. The problem with your code was that you gave the selector multiple items to listen for a change on, however each item matched with the selector, in this case two items given your example html markup, triggers the on to fire with the <input /> that had the value change.

    This code should listen for a change in any file input, then on change it will again using the same selector now scan both inputs and output the value. In this code though, it will output the path to the file, so you will need to do some regex replace or something else to get to just the filename.