0

can anyone explain why this code works:

$(document).ready(function(){
$("#file").on('change',function(){
$("#selected_files_div").append("<input type='button' class='red_button'>");
$(".red_button").on('click', function(){
// do something
});
});
});

but this one does not work?

    $(document).ready(function(){
    $("#file").on('change',function(){
  $("#selected_files_div").append("<input type='button' class='red_button'>");
    });
    $(".red_button").on('click', function(){
    // do something
    });
    });

Appending always works but click event works only in first.. case

aghtczst
  • 85
  • 1
  • 1
  • 9

1 Answers1

1

Try binding click event on parent with Event Delegation:

$("body").on('click',".red_button", function(){
   // do something
});

Read more here What is DOM Event delegation?

Community
  • 1
  • 1
Manwal
  • 23,450
  • 12
  • 63
  • 93