Catfish
Catfish

Reputation: 19284

jquery form type="file" how to tell when a file has been selected?

When a user selects a file, I want another file field to appear. It works for the first file, but if i choose a file in the second field, it doesn't get called again. Why not?

jquery script

 $(document).ready(function() {
        var i = 1;

        $('input:file[name$=\'uploadedFile'+(i-1)+'\']').change(function() {
            var file = $(this).val();

            if(file !== null && file !== "") {
                $(this).after("<input type=\"file\" name=\"uploadededFile"+i+"\" />");
                i++;
            }
        });
    });

html form

<form action="PHP/file.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
    <input type="file" name="uploadedFile0" />
    <input type="submit" value="SUBMIT" />
</form>

Upvotes: 4

Views: 527

Answers (2)

vezult
vezult

Reputation: 5243

Since this code only runs when your page is loaded, your onchange handler only applies to an input element with the name uploadedFile0. You need to extend your event handler to create a new element and bind the appropriate event handling function to it.

Upvotes: 0

SLaks
SLaks

Reputation: 887195

When you write $(...).change(function), you are adding the handler to the elements that are currently in the jQuery object. When you add a new <input>, it doesn;t have any event handlers.

You need to call .live, which will handle the event for all matching elements, no matter when they were created.
For example:

$('input:file:last').live('change', function() { ... });

Note that the selector is only evaluated once, so it won't pick up changes in i.
Instead, you should use :last.

Upvotes: 2

Related Questions