Jquery .on('change') not firing for dynamically added elements

Liam picture Liam · Oct 18, 2012 · Viewed 13.3k times · Source

So I've got a page with the following structure

<div class="editCampaignBanner">
    <div>
    <hr>
    <label for="file">Upload a new image</label>
    <input id="file" type="file" name="file" class="valid">
    <label for="NewImageURLs">Link URL (Optional)</label>
    <input id="NewImageURLs" type="text" value="" name="NewImageURLs">
    <hr>
    </div>
</div>

and I've written some jquery thus:

$('div.editCampaignBanner input:file').on('change', function () {
        var value = $(this).val();
        var div = $(this).parent();
        var html = '<div>'+ div.html() + '</div>';
        if (value.length > 0) {
            div.after(html);
        }
        else if ($(this) > 1) {
            div.remove();
        }
    });

so when I enter an element into the file it generates a div under the previous one:

    <div class="editCampaignBanner">
        <div>
        <hr>
        <label for="file">Upload a new image</label>
        <input id="file" type="file" name="file" class="valid">
        <label for="NewImageURLs">Link URL (Optional)</label>
        <input id="NewImageURLs" type="text" value="" name="NewImageURLs">
        <hr>
        </div>
        <div>
        <hr>
        <label for="file">Upload a new image</label>
        <input id="file" type="file" name="file" class="valid">
        <label for="NewImageURLs">Link URL (Optional)</label>
        <input id="NewImageURLs" type="text" value="" name="NewImageURLs">
        <hr>
        </div>
    </div>

But now, despite the event being registered using .on() the second file input in the div does not fire the event. What am I missing?

Answer

Denys S&#233;guret picture Denys Séguret · Oct 18, 2012

Replace

$('div.editCampaignBanner input:file').on('change', function () {

by

$('div.editCampaignBanner').on('change', 'input:file', function () {