4

How can i combine the following with a delegate in jQuery?

I have a #commentContainer surrounding all the editable elements, and I am dynamically adding editable fields (Jeditable). the editing ability is not working for dynamically loaded items.

     /* Bind Jeditable instances to "edit" event. */
    $(".edit").editable('/Comment/PostComment/', {
        type: 'textarea',
        cancel: 'Cancel',
        submit: 'OK',
        indicator: '<img src="img/indicator.gif">',
        tooltip: 'Click to edit...',
        event: "edit"
    });
    /* Find and trigger "edit" event on correct Jeditable instance. */
    $(".edit_trigger").bind("click", function () {
        $(this).prev().trigger("edit");
    });
laurent
  • 88,262
  • 77
  • 290
  • 428
raklos
  • 28,027
  • 60
  • 183
  • 301

2 Answers2

2

There is an solution do add jQuery.editable for dynamically added fields.

$("body").on("click",".editable",function(e){

  // Add editable plugin
  // but! for `focus` instead common `clik` event

  $(this).editable('go.to',
    {
      event : 'focus.editable',
      ..
      ..

     // Then trigger focus event

   }).trigger("focus");
 })
Jirka Kopřiva
  • 2,939
  • 25
  • 28
  • 1
    This works, but if you click more than once, editable is added again, and it messes up ... I checked for `$(this).data('editable.options')` and just triggered focus, else bind editable – Martin Jan 08 '13 at 13:39
2

Event delegation doesn't work for running code when an element is added to the DOM. Some browser event needs to first take place, like a click.

So if you're adding new elements that should have the editable plugin run against them, you'll need to call it manually as you add them.

$('<textarea>').editable( /* settings */ )
               .appendTo( '#commentContainer' );
user113716
  • 318,772
  • 63
  • 451
  • 440
  • I found this which worked too: http://forum.jquery.com/topic/loading-content-with-delegate – raklos Jan 16 '11 at 23:15
  • @raklos: Yes, but you're re-selecting all the elements from the DOM, and re-applying the plugin to those that already have it. The plugin may be equipped to deal with that, but it would be better to focus the `.editable()` calls only on those elements that require it. – user113716 Jan 16 '11 at 23:26