Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

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

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);
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...