-1

I'm trying to show a form on clicking #createbook followed by submitting the form via AJAX. For test purpose, I am trying to alert hello world on clicking #addme but its not working.But when I entered the on click function on the browser and it works. Can you guys help me figure this out. Thank you. :)

<div id="mode" style="display:none">

</div>

<script>
    $("#createbook").click(function () {
        $.get("BooksLibrary/Create #create", function (data) {
            $("#mode").html(data + '<button class="btn btn-primary" id="addme">Add Book</button>');
        });
        $("#mode").dialog({
            modal: true,
            title:'Add Book'
        });
        $("#mode").css({ "display": "block" });
    });


    $("#addme").click(function () {
        alert("hello world");
    });
</script>
Mike Corcoran
  • 12,622
  • 4
  • 31
  • 46

1 Answers1

2

As your #addme element is added dynamically (and isn't present when you create your click event), you need to delegate the event to an element which exists when you create the event. We can do this , using jQuery's on() method:

$('#mode').on('click', '#addme', function() {
    alert("hello world");
});

jQuery's website has a nice section entitled Understanding Event Delegation. The first paragraph explains what this is in a hopefully easy-to-understand way:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

James Donnelly
  • 117,312
  • 30
  • 193
  • 198