javascript - JQuery and Ajax calls on newly created elements -


i new ajax , jquery , have been doing ton of reading , cannot find solution work me.

i have jquery on.click trigger calling function via ajax update page without reloading entirely. however, these new elements being created cannot have function triggered on well.

the function below adds <tr> end of table. new <tr>'s <a> elements added cannot trigger same function after has been added.

$("a.add-department").on( "click", function(e)  {     e.preventdefault();      bootbox.dialog({         message: '<form class="form-horizontal row-border"><div class="form-group"><label class="col-md-2 control-label">name:</label><div class="col-md-10"><input type="text" id="department-name-add" value="" class="form-control"></div></div></form>',         title: "add department",         buttons: {             success: {                 label: "add",                 classname: "btn-success",                 callback: function() {                     var name = $("#department-name-add").val();;                     $.ajax({                         type: "post",                         url: "/departments/add",                         datatype: "json",                         data: 'name=' + name,                         success: function(result){                             if (result.success == 1)                             {                                 $('#table-departments > tbody:last').append('<tr id="'+result.id+'"><td id="td-'+result.id+'">'+result.name+'</td><td id="td-actions-'+result.id+'"><a data-name="'+result.name+'" data-id="'+result.id+'" data-toggle="modal" class="btn btn-xs btn-danger delete-department confirm-dialog">delete</a> <a id="a-edit-'+result.id+'" data-name="'+result.name+'" data-id="'+result.id+'" data-toggle="modal" class="btn btn-xs btn-primary edit-department">edit</a></td></tr>');                             }                         },                         error: function(result){                         }                     });                 }             },             danger: {                 label: "cancel",                 classname: "btn-danger",                 callback: function() {                     console.log('cancelled request');                 }             },         }     }); }); 

i've tried combination of using .on versus .click tying id's each element.

any thoughts?

also, know code considered ugly, trying understand how solve this.

thanks

you need use event delegation instead. way new elements added can trigger event.

here link learn more event delegation: http://learn.jquery.com/events/event-delegation/ event delegation looks this:

$(document).on("click", "a.add-department", callback) 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -