0

I am generating HTML dynamically through javascript and have 2 glyphs enclosed within a table cell. The pencil glyph responds correctly however my code for the delete does not and I am not sure why.

This is the rendered HTML

<span id="edit-dp" class="glyphicon glyphicon-pencil" data-action-url="/Settings/GetDatapoint" data-id="3"></span>
<span id="delete-dp" class="glyphicon glyphicon-trash" data-id="3"></span>

and here is my javascript code to tie the event up to the element.

$(document).ready(function(){
  $('#delete-dp').click(function (event) {
      alert('pressed');
      //add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
      deletedDatapoints.push($(this).data('id'));
  });
})
Johnathon64
  • 1,280
  • 1
  • 20
  • 45

2 Answers2

3

Use .on().

$(document).ready(function(){
    $(document).on('click', '#delete-dp', function (event) {
        alert('pressed');
        //add the datapoint ID to the array to be serialised to JSON and then stored in a html hidden field
        deletedDatapoints.push($(this).data('id'));
    });
});

You could scope it to the closest parent that is not dynamically generated to be more efficient than document.

area28
  • 1,425
  • 1
  • 9
  • 11
  • This uses "event delegation". The problem that OP is experiencing is related to the element not existing when the JavaScript is run. Delegation avoids this by using event propagation. – raynjamin Jun 29 '15 at 15:27
  • @area28 I have no idea why but this works, thanks! Can you explain why this works as opposed to why my first approach did not work? – Johnathon64 Jun 29 '15 at 15:33
  • 1
    Check out [this doc](http://learn.jquery.com/events/event-delegation/) about event delegation. This explains it very well. – area28 Jun 29 '15 at 15:35
0

To handle dynamicly added events use

$('#delete-dp').on('click',function(event){
    //do your stuff
});
depperm
  • 10,606
  • 4
  • 43
  • 67