user2810718 user2810718 - 1 year ago 51
jQuery Question

on click event not firing for dynamically added button inside tab

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 ) {

var active = $( "#tabs" ).tabs( "option", "active" );
if(active == 0){ //add toolbar to tab index = 1

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() {

} );

The code is inside a document ready function.Could someone help me to catch the onclick event for the button?

Answer Source

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.