Insert a file entry item using jQuery


I'm having trouble inserting file input elements with jQuery. What I want to happen is when a user selects a file using the input element, jQuery should hide that input and insert a new file input in its place.

Here's my relevant markup:

<div id="select_images">
    <input type="file" name="images[]" multiple="multiple" />

And my Javascript:

$('#select_images input').change(function(){
    // User selected some images to upload, hide this file input
    $(this).css('right', '-10000px');

    // Insert a new file input to take its place
    $('#select_images').append('<input type="file" name="images[]" multiple="multiple" />');

It kind of works. When I select a file using the file input already on the page, jQuery hides it and inserts a new one. When I try to do the same again however, jQuery does not insert a new file input.

I can't see any reason that the above code will only insert one additional file input, so I'm pretty stumped. I've confirmed this behaviour using both Firebug and POSTing the form data to my backend script.

Any help is appreciated. Thanks!

try using live

$('#select_images input').live('change',function(){...

when you dynamically add the elements to the DOM the event handlers do not automatically get attached to them, to attach the event handlers to the dynamically added elements you can use .live or .delegate

example with delegate

//handler code here




When You Should Use jQuery’s Live and Delegate Methods