0

Following is my code. After appending buttons in div, the appended buttons click event not working.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    <button class='btn-append'>Append Buttons</button><br><br>
    <div id='div-buttons'> </div>
    <script>
      $(document).ready(function(){
        $('.btn-append').click(function(){
          var content = "<button class='btn'>Button-1</button><br><br><button       class='btn'>Button-2</button>";
          $('#div-buttons').append(content);
        })
      });

      $(document).ready(function(){
        $(".btn").click(function(){
            $(this).hide();
        });
      })
    </script>
   </body>
</html>
Nishant
  • 35
  • 8

1 Answers1

1

You need to bind the event as at page load the element was not having existence so the event was not binded.

$(document).ready(function(){
        $('.btn-append').click(function(){
          var content = "<button onclick='hideButton(this)'>Button-1</button><br><br><button class='btn'>Button-2</button>";
          $('#div-buttons').append(content);
          $(".btn").unbind();
          bindBtnClass();
        });
      });
      
      function bindBtnClass(){
        $(".btn").bind('click', function(){
            $(this).hide();
        });
      }

function hideButton(elem){
    $(elem).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-append'>Append Buttons</button><br><br>
    <div id='div-buttons'> </div>

Cheers..!!

Moreover you can directly use implementation done in button 1.

Rush.2707
  • 622
  • 10
  • 26