Reputation: 71
I have a page with 2 tabs. Each tab is loaded with its own DataTable and toolbar controls. Depending on which tab is active, I dynamically add the appropriate toolbar(with custom buttons). However the onclick event does not fire for the dynamically added elements inside the tabs. Below is the code I am using to add the controls to different tabs:
$("#tabs").tabs( {
active: 0,//Tab no.2 "Sha-2" by default active on page load,
"activate": function(event, ui) {
var table = $.fn.dataTable.fnTables(true);
if ( table.length > 0 ) {
$(table).dataTable().fnAdjustColumnSizing();
var active = $( "#tabs" ).tabs( "option", "active" );
if(active == 0){ //add toolbar to tab index = 1
$("div.toolbar").html('');
}
if(active == 1){ //add toolbar to tab index = 1
$("div.toolbar").html('<a id= "add-vendor"class="ui-button ui-widget ui-corner-all">ADD VENDOR</a><a id= "create-purchase_order"class="ui-button ui-widget ui-corner-all">CREATE PO</a>');
$( "#add-vendor" ).button().on( "click", function() {
alert('hello');
});
}
}
}
} );
The code is inside a document ready function.Could someone help me to catch the onclick event for the button?
Upvotes: 0
Views: 930
Reputation: 1059
$(document).on('click', "#add-vendor", function() {
alert('hello');
});
Will do the trick, delegate the event to the document for dynamically added elements.
Upvotes: 1
Reputation: 176
It does not work because you are converting anchor tag to a button. If you remove the button method then it works correctly :
$("div.toolbar").html('<a id= "add-vendor"class="ui-button ui-widget ui-corner-all">ADD VENDOR</a><a id= "create-purchase_order"class="ui-button ui-widget ui-corner-all">CREATE PO</a>');
$( "#add-vendor" ).on( "click", function() {
alert('hello');
});
If you want to use button then create a button tag instead of anchor tag.
Upvotes: 1
Reputation: 1743
you need to delegate the dynamically added buttons:
$(*ParentOfTheDynamicallyAddedButton*).delegate("DynamicallyAddedButton", "click", function(){
*your function*
}
You could say your browser is unaware of dynamically added elements, as they are not part of the script. they only exist in the DOM and therefore have no script attached to them. but don't quote me on that, im a noob.
Upvotes: -1