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

老子叫甜甜 提交于 2019-11-29 10:56:06

Replace

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

by

$('div.editCampaignBanner').on('change', 'input:file', function () {
$(document).delegate("div.editCampaignBanner input:file", "change", function() {
  //code goes here
});


$(document).on('change', 'div.editCampaignBanner input:file', function () {
 //code goes here
});

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method.

Differences Between jQuery .bind() vs .live() vs .delegate() vs .on()

try this:

$('div.editCampaignBanner').on('change','input:file', 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();
        }
    });
Amit Kriplani

May be use $.live() jquery method, its deprecated but works for me:

$('div.editCampaignBanner input:file').live('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();
        }
    });

more info : http://api.jquery.com/live/

if you are reluctant on using the latest (.on()) use it like this :

function fileChanged(ele){
    var value = ele.val();
    var div = ele.parent();
    var html = '<div>'+ div.html() + '</div>';
    if (value.length > 0) {
        div.after(html);
    }
    else if (ele > 1) {
        div.remove();
    }
    $('div.editCampaignBanner').unbind().on('change','input:file', function () {
        fileChanged($(this))
    });
}
$(function(){
    $('div.editCampaignBanner').on('change','input:file', function () {
        fileChanged($(this))
    });
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!