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

4
  • 1
    This question has been asked and answered many times. You have to use delegated events (learn.jquery.com/events/event-delegation). Commented Aug 30, 2016 at 10:29
  • thanks kosmos.. will go through the link for better understanding Commented Aug 30, 2016 at 11:03
  • you're welcome. once you read it you'll see that's really easy. Commented Aug 30, 2016 at 11:04
  • Possible duplicate of Event binding on dynamically created elements? Commented Aug 30, 2016 at 11:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.