0

I create a list of buttons with this instruction:

$("ul#cards").append("<li><button id="modifiedCard" type="button" class="btn btn-primary btn-xs pull-left">Modified</button></li>");

Ok, it works. Buttons are generated correctly.

In the same page I wrote:

$("#modifiedCard").click(function () {
    alert("Hello!");
});

But, when I click on one of them the alert doesn't start.

I tried with:

<button id="modifiedCard">Try</button>

and the alert starts.

Why?

Dave
  • 1,428
  • 4
  • 31
  • 49

2 Answers2

2

You need to use event delegation for attaching events to dynamically added DOM:

$("ul#cards").on('click','#modifiedCard',function () {
  alert("Hello!");
});

Also note that you are appending the elements. That will generate buttons with same ID. which is invalid markup. IDs should be always unique. I would rather suggest you to use modifiedCard as classname instead of ID

$("ul#cards").append("<li><button type="button" class="modifiedCard btn btn-primary btn-xs pull-left">Modified</button></li>");

and then use class selector for event delegation. Like this:

$("ul#cards").on('click','.modifiedCard',function () {
  alert("Hello!");
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Delegate events for the dynamically created elements:

$(document).on('click', '#modifiedCard', function () {
  alert("Hello!");
});

Or specifically:

$("ul#cards").on('click', '#modifiedCard', function () {
  alert("Hello!");
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252