0

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
comfreakph
  • 549
  • 2
  • 6
  • 20
  • 1
    what is the issue? You are reading the files from the input that was changed. – epascarello May 11 '18 at 03:00
  • **I think my code is in getting the files is wrong** What you mean by this phrase is not clear at all. So, what the JS you wrote does so far is *whenever the file of an input is changed, you alter the file names that is selected into each file input control.* Is this what you want? – Romeo Sierra May 11 '18 at 03:08
  • yes, I want to get the files from all input file control, coz the system generating dynamic controls. do I need to do loop to read all the input file elements? – comfreakph May 11 '18 at 03:37
  • So you mean these `` are created **after** `document.ready` right? – Kaiido May 11 '18 at 03:58
  • Won't hammer before your confirmation but *Possible duplicate of [event handler not working on dynamic content](https://stackoverflow.com/questions/15090942/event-handler-not-working-on-dynamic-content)* – Kaiido May 11 '18 at 04:01
  • yes, but I already able trigger the event on change for input file, my problem was getting the file data to all input file. – comfreakph May 11 '18 at 04:11
  • Ok, I wonder why you would ever want to do that, but... – Kaiido May 11 '18 at 04:13

1 Answers1

1

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.

Tom Bird
  • 999
  • 3
  • 17
  • 31