null
null

Reputation: 35

Jquery not working on dynamically added button?

$(document).ready(function(){
    var t = $("<div><button class='leaf' id='l2'>Awesome!</button></div>");
   $('#l1').click(function(){
       $('#num').text("four");
       }); 
    $('.oright').click(function(){
       $('#num').text("Five");
       $('.oright').after(t);
       $('.oright').remove();
    });
    $('#l2').on('click', function(){
       $('#num').text("Reset?");
    });
});

The #l2 button doesn't have any functionality. I don't see any Syntax error, I looked it up and read that .on('click') was better than .click for dynamic elements, so I changed that but it still doesn't work.

Upvotes: 0

Views: 43

Answers (2)

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

Because you have defined the new button markup as a jquery object - t - you can assign the click handler to it.

$(document).ready(function(){
    var t = $("<div><button class='leaf' id='l2'>Awesome!</button></div>");
   $('#l1').click(function(){
       $('#num').text("four");
       }); 
    $('.oright').click(function(){
       $('#num').text("Five");
       $('.oright').after(t);
       $('.oright').remove();
    });

    /* use the t jquery object you have defined */
    t.on('click', function(){
       $('#num').text("Reset?");
    });
});

Or delegate as @adeneo shows well

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You'll have to delegate to make that work

$(document).on('click', '#l2', function(){
   $('#num').text("Reset?");
});

preferably you'd replace document with the closest non-dynamic parent element

Upvotes: 1

Related Questions