1

I am trying to extract the id=obj1 from the string html_doc and trying to attach an onclick function to it

document.addEventListener("DOMContentLoaded",
function (event) {
    $ajaxUtils.sendGetRequest("data/GOG123.json", 
        function (res) {
            var residue=res.residues;

            var html_doc = "<div>" + "<Button id = obj1>" + residue[0].index + "</Button> " + "</div>";
            console.log(html_doc);

            var html_doc2;

            html_doc2= $("html_doc").find("obj1");
            $(document).ready(function(){
                html_doc2.click(function () {
                    alert("Hello!");
                });
            });

            var div1=$("#infoDiv");
            div1.append(html_doc);
        }
    );

});

It is not working (i.e not showing an alert message) neither it is throwing any error.

Can someone please help me with the same?

I referred to Why is this jQuery click function not working? but it did not work out for me.

vamsiampolu
  • 6,328
  • 19
  • 82
  • 183
Mansi Mehta
  • 23
  • 1
  • 3

2 Answers2

1

Try to put ajax in either function or inside document ready.without extracting id you can do same thing if you know id.

var html_doc = "<div>" + "<Button id = obj1> Click" + "</Button> " + "</div>";//instead of click put ur code
var div1 = $("#infoDiv");
div1.append(html_doc);

$(document).ready(function() {
  $("#obj1").click(function() {
    alert("Hello!");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=infoDiv>This is div info</div>
Aishwarya
  • 637
  • 9
  • 21
1

you can also use .on() click event.

$(document).on("click", "#obj1", function(){
    alert("clicked");
}); 
Ashish Mehta
  • 7,226
  • 4
  • 25
  • 52