2

One button, when clicked, changes the html in the body tag, in which there is a new button. New button, when clicked, should give an alert message, but it is not.

I think it's probably the document.ready part, which needs to be reinitialized. But i don't know how to do that. Please check the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Title For the Website</title>
    <script src="js/jquery-2.1.4.min.js"></script>
  </head>
  <body>
    <div id="bigbox">
      <button id="idol">Idol</button>
    </div>
    <script>
      $(document).ready(function(e){
        $('#idol').click(function(event) {
          console.log("success");
          var x = '<button id="clickhere">Click Here!</button></div></div>';
          $('#bigbox').html(x);
        });

        $('#clickhere').click(function(event) {
          alert('This is working');
        });
      });
    </script>
  </body>
</html>

This is a cut down version of my code. In the original page, a button generates some html through an ajax call, and that html has a button to do another ajax call.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
notANerdDev
  • 1,284
  • 11
  • 28

4 Answers4

4

Use event delegation as follow:

$(document).on('click', '#clickhere', function(event) {
    alert('This is working');
});

This happened because your button was dynamically added, so it wasn't in the dom. The event delegation will ensure that event get delegated from document to button.

Nikhil Batra
  • 3,118
  • 14
  • 19
  • Alright! I used it, and it works. I have used this style of writing in other work, but i just don't understand why my way doesn't work? Any reasoning for that? – notANerdDev Jul 08 '15 at 11:38
  • 1
    Your style of writing means writing in dom ready and not using event delegation? – Nikhil Batra Jul 08 '15 at 11:40
1

The #clickhere is a dynamically generated content. So you need to delegate the events:\

$('body').on("click", "#clickhere", function(event) {
  alert('This is working');
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Just cut and paste the code inside the button generating function

It will attach click event to dynamically generated button

 $(document).ready(function(e){
        $('#idol').click(function(event) {
            console.log("success");
            var x = '&lt;button id="clickhere">Click Here!&lt;/button>&lt;/div>&lt;/div>';
            $('#bigbox').html(x);
            $('#clickhere').click(function(event) {
                alert('This is working');
            });
        });


    });
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
Unni Babu
  • 1,839
  • 12
  • 16
0

Try

    $("#clickhere").bind("click",function(event){
 alert("working");
});
Govind Mantri
  • 803
  • 1
  • 11
  • 24