jquery click event not working for dynamic fields [duplicate]

蓝咒 提交于 2019-12-05 02:21:05

You'll need to use event-delegation:

$("table").on("click", ".btnDel", function () {
    /* Respond to click here */
});

The reason is that you cannot bind a handler to items that don't presently exist in the DOM. You can, however, bind a handler to a delegate target (a parent element that will remain in the DOM). Clicks will bubble up the DOM, eventually reaching the delegate target.

We listen for clicks on the table and we evaluate whether they came from an .btnDel element. This will now respond to clicks from .btnDel elements loaded when the page loaded, as well as those that are added dynamically later.

Lastly, don't re-use ID values.

You need to use on() for event delegation for dynamically added html elements. You can delegate event to parent element of dynamically added elements if you can or you can delegate to document.

$(document).on('click', '.btnDel', function () {
    alert('hey');
    console.log('test');
    var row = $(this).closest("tr");
    alert(row);

    row.remove();
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

For further understanding read this article Understanding Event Delegation

use on()

$(document).on('click', '.btnDel', function(){
  //your code
})

This will work

    $('#btnAdd').click(function () {

       var newTr = '<tr><td><input id="column_0" 
       name="column[0]"style="width:40%;"type="text" />
      <img alt="Delete-icon24x24" class="btnDel clickable" id="" 
       src="/assets/delete- icon24x24.png" /></td></tr>';
    $('#columns').append(newTr);

       $('.btnDel').click(function () {
       alert('hey');
       console.log('test');
       var row = $(this).closest("tr");
       alert(row);

       row.remove();
     });



      });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!