None

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 http://drumcoder.co.uk/blog/2010/mar/11/dynamic-css-popup-jquery/

CSS

Here's the CSS required.

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

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

JavaScript

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();
    $(this).after(textarea+button).remove();
    $('#new_title').focus();
    $('.saveButton').click(function(){
        var lNewTitle = $('#new_title').val();
        window.needs_refresh = true;
        $.post("/task/change/{{TaskCard.id}}/", {title: lNewTitle}, function(txt){
            $('#popup').load('/task/details/{{TaskCard.id}}/');
        });
    });
    $('.cancelButton').click(function(){
        $(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.