0

I have a very basic doubt...
In my wordpress blog, in my custom metabox,
This is my event handler :

jQuery('tr input.test').on('click', function( event ){
    event.preventDefault();
    var index = jQuery(this).closest('tr').index();
    set_row_index(index);
    .
    .
    .
    });

I have a table with last column having button (input type->submit) "Edit". On adding a row dynamically, the "Edit" button of newly added row does not works.

jQuery('tr #confirm_add').on('click',function(){
   event.preventDefault();

  .
  .
  .
   html += "<td> <input type=\"submit\" id=\"select\" value=\"Edit\"></td>";
   .
   .
   .
   $('#metabox_row').prepend(html);

   // BIND ELEMENT HERE
});

I need to bind this event handler to the Edit button. Please help on how to achieve this

cosmoloc
  • 2,884
  • 5
  • 29
  • 48
  • 1
    This question has been asked and answered many times. You have to use delegated events (https://learn.jquery.com/events/event-delegation/). – kosmos Aug 30 '16 at 10:29
  • thanks kosmos.. will go through the link for better understanding – cosmoloc Aug 30 '16 at 11:03
  • you're welcome. once you read it you'll see that's really easy. – kosmos Aug 30 '16 at 11:04
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – hjpotter92 Aug 30 '16 at 11:37

1 Answers1

1

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.

Script

$('#metabox_row').on('click', "input.select'", function(){
    //Your code
});

Change the type to button

html += "<td> <input type=\"button\" id=\"select\" value=\"Edit\"></td>";

The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Satpal
  • 132,252
  • 13
  • 159
  • 168