0

I need to add a form to a page when the user clicks a button. I am making a string of that html and then adding it to the div using jQuery. (I've read somewhere this is not the best method, so please tell me an alternative).

However, the problem is this - The new html that I am adding has a button with id id1. The script that I try to call, does not get called when I do this-

$(document).ready(function(){
$("#id1").click(function(){
    alert("hi");
});

This may be happening because I have written this inside document.ready(), and by the time document gets ready, no element with id id1 exists. How can I mitigate this problem?

kshubham07
  • 341
  • 1
  • 3
  • 15

1 Answers1

1

Delegate the event.Here on is used to attach an event handler function

$("body").on("click","#id1",function(){
    alert("hi");
});
brk
  • 48,835
  • 10
  • 56
  • 78