Catch change event on input field dynamically added to Jquery Datatables table

爷,独闯天下 提交于 2019-12-01 01:28:18

问题


I have an ajax call that uses the following code to add some rows to a data table for each record in the response:

strAppName = data.Application_Name
maintCost = '<input class="maintCostField" appid="' + data.Application_ID + '" type="text" placeholder="$">';

$('#myReport').dataTable().fnAddData([
    strAppName,
    maintCost,
    etc,
    etc
]);

I've tried the following selectors/events to catch changes to the text box, but none of them trigger. They are in the document.ready section...

$(".maintCostField").bind('change',function () {
    val = $(this).val();
    app = $(this).attr('appid');
    alert('Updating app# ' + app + ' with ' + val);
});


$(".maintCostField").on('change',function () {
    val = $(this).val();
    app = $(this).attr('appid');
    alert('Updating app# ' + app + ' with ' + val);
});

(I know this one is deprecated)

$(".maintCostField").live('change',function () {
    val = $(this).val();
    app = $(this).attr('appid');
    alert('Updating app# ' + app + ' with ' + val);
});

What am I doing wrong? I don't see why it's any different than Click event doesn't work on dynamically generated elements or many others...

update* I added the following to the fnDrawCallback event of the datatable and now it works, only it executes as many times as there are forms on the screen.

$(".maintCostField").each(function () {
    this.addEventListener("change", function () {
        val = $(this).val();
        app = $(this).attr('appid');
        alert('Updating app# ' + app + ' with ' + val);
    }, true);
});

回答1:


The answer to that question is actually wrong. (He updated the answer!) You have to bind the event to a parent element because the input doesn't exist yet in order to bind the event to.

$(document).on('change', '.maintCostField', function() { 

FIDDLE




回答2:


you can also use $(document).on('input', '.maintCostField', function () {



来源:https://stackoverflow.com/questions/16225336/catch-change-event-on-input-field-dynamically-added-to-jquery-datatables-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!