Reputation: 1310
I had trouble to activate related JavaScript / jQuery event when the part of the page is loaded with dynamically created button. How can I resolve this issue? What is the best method to resolve this issue?
It is base on my trouble in real case.
I have this function to call the php function to generate a new dynamically create pagination section in a page with Ajax.
function loadData(page){
$.ajax({
type: "POST",
url: ".../get_Scorewithagination.php",
data: 'page='+page+'&testID='+testID+'&testDate='+testDate+'&empPass='+empPass+'&courseCode='+courseCode,
success: function(msg){
$('#testInfo').empty();
$(document).ajaxComplete(function(event, request, settings){
loading_hide();
$("#resultBox").html(msg); to #resultBox
});
$('.iconpoint_orange').click(function() {
btnNames = $(this).attr("name").split("_");
$.post('.../getInfo.php', {testresult: btnNames[1]}, ShowTestInfo);
});
// Collapse row on delete
$('.iconpoint_blue').click(function() {
alert();
rowName = this.name;
rowID = '#' + rowName;
$(this).closest('tr').children('td').addClass("row_hover");
$("#dialog_confirm").html("Are you sure you want to delete this?");
$("#dialog_confirm").dialog({
buttons : {
"Delete" : function() {
$(rowID).closest('tr').animate({opacity: 0},500).slideUp(300);
setTimeout(function() {$(rowID).closest('tr').empty().remove();} ,3000);
$(this).dialog("close");
},
"Cancel" : function() {
$(rowID).closest('tr').children('td').removeClass("row_hover");
$(this).dialog("close");
}
}
});
$("#dialog_confirm").dialog("open"); // Show dialog box
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
$('#testInfo').html("<br\>Status: " + textStatus +"<br\>Error: " + errorThrown);
$('#testInfo').addClass("errorRed");
}
});//$.ajax() END
}//loadData(page) END
But the issue is that those two buttons
.iconpoint_blue
and
.iconpoint_orange
are not be able to call for a respond after the rows are dynamically generated by php file I called with Ajax.
I know that Ajax returned html codes are not scanned by JavaScript at the beginning of the document complete since it was completed later, therefore, the button I created dynamically will not respond to the function even its the correct selector #
.
I want the dynamically generated button with existing function's selector for each record, will be able to call back the function that is loaded at page load?
Upvotes: 2
Views: 585
Reputation: 1055
Bind the function to a parent element. For example, with this HTML:
<div class='wrapper'>
<a href='#' class='click_here'>click here</a>
</div>
you could have the following javascript:
$('.wrapper').on( 'click', '.click_here', function() {
$(this).after('<a href="#" class="or_here">or here</a>');
});
$('.wrapper').on( 'click', '.or_here', function() {
$(this).remove();
});
Here's a jsFiddle.
Upvotes: 4