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

1.4k views Asked by At

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.');
    });
3

There are 3 answers

4
Blender On BEST ANSWER

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.

0
Rafal On

One of the solutions is to add a hidden div with a textbox in it.

<div style="display:none; id="textbox_container">
<textarea id="box"></textarea>
</div>

Then in your click function, you show the textbox

$("#textbox_container").show();

You can update the value of the textbox with .val("")

Hope this helps.

4
Loktar On

There are two ways to do this, in modern browsers you can use contenteditable=true, and then on blur send the new contents on their way. This takes care of having to swap out a textarea.

<div contenteditable="true">Some Text</div>

or you can do it the js way.

http://jsfiddle.net/2RyT2/23/

$(function(){
    $("#meText").live('click',function(){
        var originalDiv = this;
            $(this).replaceWith($("<textarea></textarea>").text($(this).text()).width($(this).width()).height($(this).height()).blur(function(){$(this).replaceWith($(originalDiv).text($(this).val()));}));
    });
});