0

I have created a table and want to get an id on a td click. The data is population through an ajax call and I an want an id on when delete is clicked. So its on the fly the elements are added.

$.ajax({
        url: 'http://localhost:8080/getUsers,
        type: 'GET',
        success: function (data, textStatus, jqXHR) {
            $.each(data, function (index, result) {
                $("<tr></tr>").attr("id",result.user_id+"userTr").appendTo("#userTBody");
                $("<td></td>").attr("id",result.user_id+"userName").appendTo("#"+result.user_id+"userTr");
                $("#"+result.user_id+"userName").html(result.username);
                $("<td></td>").attr("id",result.user_id).appendTo("#"+result.user_id+"userTr");
                $("#"+result.user_id).html('Delete');
                $("#"+result.user_id).css('cursor', 'pointer');
                $("#"+result.user_id).addClass("delete");
            });
        },
        error: function() {
            alert('err')
        }
    });

$('.delete').on('click', function () {
        alert($(this).attr('id'));
    });

I have also tried with this.id but nothing happens.

JN_newbie
  • 2,760
  • 8
  • 45
  • 79
  • Yep, read the post linked above, you want to switch your notation from delete.on click to document.on click '.delete' – Caleb O'Leary Apr 19 '16 at 14:19
  • @Tushar, I have a question why with the document .on instead of simple $('delete').on? because of dynamically created elements in a DOM? – JN_newbie Apr 19 '16 at 14:33
  • 1
    @Java_NewBie Please read the answers on the stated question. Also read about [Event Delegation](https://learn.jquery.com/events/event-delegation/) – Tushar Apr 19 '16 at 14:34

1 Answers1

2

Try this:

$(document).on('click', '.delete', function () {
    alert( $(this).attr('id') );
});
PeterKA
  • 21,234
  • 4
  • 21
  • 44
  • Please don't answer such obvious dupe questions if you can't add anything to existing answers, close it instead. – Tushar Apr 19 '16 at 14:20