1

Really simple question here, kills me to ask it. I just cannot fix it.

In an ajax call I want to show a list of items. Each item will have a button.

So I put this div in my HTML:

<div id="calendar">
  <div id="activity_wrapper">
    <h4 class="activity-name"></h4>
    <p class="activity_start"></p>
    <p class="activity_end"></p>
    <a class="start" id="start">Start Activity</a>
    <a class="finish">Complete Activity</a>
    <button id="delete-activity-button" class="delete" value="">Delete</button>
    <button id="modify-activity-button" class="modify" value="">Edit</button>
  </div>
</div>

Now in jQuery with Ajax I create the list like so:

$.each(data, function (index, activity) {
  var newActivity = activityDiv.clone();
  var startTime = new Date(activity.startDateTime);
  var endTime = new Date(activity.endDateTime);

  newActivity.find(".activity-name").text(activity.name);
  newActivity.find(".activity_start").text(startTime);
  newActivity.find(".activity_end").text(endTime);
  newActivity.find(".delete").val(activity.id);
  calendar.append(newActivity);
});

Then finally I have this onclick:

$('.delete').click(function(e) {
  var selected = $(this).attr('class') || $(this).attr('id');
  var id = selected.val();
  alert(id);
});

The click will not register. What am I doing wrong? I believe it is due the way I clone the activity class.

Thanks.

Shiladitya
  • 11,210
  • 15
  • 22
  • 33
jackabe
  • 293
  • 4
  • 21

1 Answers1

0

You shouldn't use clone() on elements containing IDs since IDs should be unique. Also, your click handler is trying to work with the ID which is going to have inconsistent behaviour because of the multiple identical IDs.

Clone() also isn't going to clone the events you've attached to your initial div (unless you pass it 'true'), so your click handler isn't going to fire, depending on when you attached it. It would be better to attach your click handler to the parent:

$('#calendar').on( 'click', '.delete', function(e) { ... } );

so you don't have to worry about cloning the event on every activity.

Colin
  • 341
  • 7
  • 15