Search code examples
jqueryajaxedit-in-place

How to add a text box in a div with a value with jquery (edit in place)


HI, I'm trying to add edit in place functionality to my site with jquery. I don't want to use a plugin, so my idea was that when you click the div that has the content in it, it would replace the div with a text box, then on blur it would submit a post to save the content.

So far I have the click event, but I'm not sure how to replace the div with a text box, and then make it submit on blur, I can probably figure out the ajax request though.

Any help would be great, thanks. So far this is what I have... just the click event:

$('.control-panel-profile-update').click(function() {
      alert('Handler for .click() called.');
    });

Solution

  • It's not completely written, and it might not completely work, but it's worth a shot. Good luck:

    $('.control-panel-profile-update').live('click', function() {
      $(this).replaceWith('<input type="text" id="inlineEdit" value="' + $(this).html() + '" />');
    
      $('#inlineEdit').focus().live('blur keyup', function(event) {
        if (event.keyCode && event.keyCode != 13) return false;
    
        $(this).replaceWith('<div class="control-panel-profile-update">' + $(this).val() + '</div>');
      });
    });
    

    Here's a Fiddle: http://jsfiddle.net/Af6X6/2/. I added support for the enter key too.