ztit ztit - 3 months ago 10
Javascript Question

Bind/Unbind element to JS Event Handler with unnamed function

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

Answer

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.