Joyal
Joyal

Reputation: 2693

jquery "on" issue on dynamic item

I have a jquery

$(document).ready(function(){

        $(".files").on('change', function() {
            $('.file_fiels').append('<li><input type="file" name="attachments[]" multiple="multiple" class="files" /></li>')
        }); 

    })

and HTML

<ul class="file_fiels">
<li><input type="file" name="attachments[]" multiple="multiple" class="files" /></li>
</ul>

which means, when somebody add an item to input, another input type should show up.

Its working perfectly with the first input type, it doesn't work with the input that is created when I add on item on the first input type.

Upvotes: 0

Views: 59

Answers (3)

D.S
D.S

Reputation: 1150

I have always used .live() for dynamic items, it worked pretty much flawlessly for me.

Upvotes: 0

bipen
bipen

Reputation: 36531

use on event delegate for dynamically added elements

$('.file_fiels').on('change', '.files', function() {
   $('.file_fiels').append('<li><input type="file" name="attachments[]" multiple="multiple" class="files" /></li>')
});

read more about on delegate events

Upvotes: 2

VisioN
VisioN

Reputation: 145408

Since parent <ul> element is static, you can use event delegation:

$(".file_fiels").on("change", ".files", function() {
    $(".file_fiels").append("<li> ... </li>");
});

Upvotes: 1

Related Questions