jQuery Edit In Place

March 11, 2010

To make it easy to edit text, we can display it, and then when clicked we can replace it with a small form. This allows the user to edit the text, and when they click Save we can update it on the server using a bit of AJAX, and then refresh the page.

This solution goes hand in hand with the poup specified at


Here's the CSS required.

#CardName:hover {
    background-color: #6094DB;

This shows a different background colour when something that is editable is moused over.


This code picks up a click on the editable text, and replaces it with the edit dialog.

$('#CardName').live('click', function(){
    var textarea = '<div><input id="new_title" type="text" maxlength="50" size="40" value="' + $(this).text() + '"/>';
    var button = '<div><input type="button" value="Save" class="saveButton" /> 
                                              or <input type="button" value="Cancel" class="cancelButton"/></div></div>';
    var revertHtml = $(this).text();
        var lNewTitle = $('#new_title').val();
        window.needs_refresh = true;
        $.post("/task/change/{{}}/", {title: lNewTitle}, function(txt){
        $(this).parent().parent().after('<h3 id="CardName">'+revertHtml+'</h3>').remove() ;

Note that this code attaches an event with live() rather than bind(). Bind() only works with elements that are already on the page - if you are dynamically adding new elements that match the selector, these will not have the click event attached. Using live(), any new matches added to the DOM at runtime will have the appropriate event added.