2

I was creating a dynamic table where a new row is added on a button click. This table contains a column called Delete. Whenever, delete a-link is clicked, the corresponding row is to be deleted. But my jquery is not working.

The snippet that deletes entry from table is:

$(".delRow").click(function()
                        {
                            alert("Called");
                             $(this).parents('tr').first().remove();


                        }
                    ); 

Here is the jsfiddle LINK

Update: Please Note I am successfully able to delete those row which are not added dynamically. Even the alert is not invoked when I click on Delete a-link column of the row added dynamically.

kbvishnu
  • 12,180
  • 17
  • 64
  • 97
Ritesh Kumar Gupta
  • 4,525
  • 6
  • 39
  • 68
  • possible duplicate of **[Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)**. This question is asked 4/5 times every single day. – dsgriffin Jul 16 '13 at 09:18

3 Answers3

4

Since the .delRow is not present at the time the page loads you need to use .on to bind the event handler to dynamically created elements.

To use this form of on we first use jQuery to select an existing static parent of the element we would like to bind our event handler. The chosen parent should be as close to the target element as possible to improve performance. We next specify the events that should be handled and the selector for our target element. Finally, the event handler is provided.

            /*Remove Text Button*/
            $("#sample-table").on("click", ".delRow", function()
                {
                    $(this).parents("tr").remove();
                }
            ); 

Working Example http://jsfiddle.net/qRUev/2/

Documentation

Kevin Bowersox
  • 88,138
  • 17
  • 142
  • 176
  • 2
    hey this is correct, but why not $(this).closest('tr').remove(); instead of $(this).parents("tr").remove();, as closest will improve the performance – RONE Jul 16 '13 at 09:32
  • @ravi-mone can you provide some documentation that it will improve performance? I'm interested in it but I must say I don't know what to look for exactly. – José Oct 05 '15 at 17:58
2

Try to use

$('.delRow').live('click', function (){
   alert("Called");
});

instead of

$(".delRow").click(function(){
   alert("Called");
});
Deepu
  • 11,425
  • 13
  • 53
  • 87
Gemini
  • 89
  • 1
1

you may need to use

$(document).on('click', ".delRow", function()
                    {
                        alert("Called");
                         $(this).parents('tr').first().remove();


                    }
                ); 

Demo: Fiddle

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504