In-line Text Editing with jQuery Tutorial

This is my first “tutorial”, so bear with me, or even send me comments, if it totally sucks. I was playing around, and needed an inline editor, just for fun, not really because I needed it. I looked for an existing script, but didn’t see any I liked. So I made one with JavaScript/Ajax, PHP, and HTML. The short description of it: show the items in plain HTML text, but when clicked, turn the text into an editable text box, and save changes to it when the user clicks or tabs out of the box (yes, onBlur.) THIS IS NOT A PHP TUTORIAL, it’s focus is on JavaScript/Ajax, I’m trusting the PHP to you!

  • I love jQuery, so the first step is to download that and put it on your server.
  • Next, you’ll need the HTML for the stuff you’ll want to edit. Here’s what mine looked like:
    <input value="<?php echo $id; ?>" id="nameID" type="hidden" />
    <span class="editName"><?php echo $name; ?></span>
    <input id="newName" name="editName" style="display: none" type="text" />

    * Note that I’m leaving out the part where you connect to your database, return a result set, and set the “$name” and “$id” variables. The hidden id is a unique identifier for the entry in your database that you should return in your result set so we know which row to update in the db.

    The important part of this HTML is that you have a class (or you could use an ID) containing your editable content, and you have a hidden text box with the same value, with its display set to none.

  • Now, the magic happens. We need to set up an onClick event for our span to make the span disappear and the text box appear. Here’s how jQuery does that for us (put this in a script tag in your page head, right after your link to the latest version of jQuery):
    $(function(){
        $("span.editName").click(function(){
    
        });
    });

    Pretty simple - the first line is the standard jQuery function, the next line says when you click on a span with the class of editName, do a function.

  • Next, we build the onClick function:
    $(function(){
        $("span.editName").click(function(){
            $(this).hide();
            $(this).next("input#newName").show().focus();
        });
    });

    Use jQuery to hide the span, and show the text box (and put the cursor in it).

  • Now the user edits the text box and then leaves the text box. Time to use jQuery’s $.ajax function, you can put this onBlur event inside the main $(function(){ }); function, right after your click function:
    $("input#newName").blur(function(){
        var nameID = $("input#nameID").val();
        var newName = $("input#newName").val();
        $.ajax({
            type: "POST",
            url: "updateName.php",
            data: "nameID=" + nameID + "&newName=" + newName,
            cache: false,
            success: function(message){
                alert(message);
                window.location.reload(true);
            }
        })
    });

    OK, it looks like a lot happened here, let’s break it down. First, we create two variables with the id of the row to update, and the new name to use. Next we get into the $.ajax function - tell the function to use the POST method. Then enter the url of the PHP script we made to update the db (probably has a SQL statement to ‘update tbl_name where id = $nameID, set name = $newName’ or something like this.) Next we pass the data, our two variables from the last step. Then we make sure the browser is not cahcing the page. Finally, we have a success function. I am assuming there will be success for the simplicity of this tutorial, you can read up on jQuery to see how to handle failures. You alert the message, and reload the page so the new name is showing in the span and the text box is gone. Important: the success function takes a message parameter, this is what your updateName.php script echoes, so you should have it echo something that makes sense like “Name updated!” on success, or a graceful error message if the update doesn’t work.

This is of course a simplified version of how to accomplish inline editing, it does not take into account every potential roadblock or hazard, or scenario, so please tinker with it, customize it, and strengthen it. It’s just a building block, I hope you enjoy it! *Aside: this is modified from my working code, and I did not test it thoroughly, so it has potential to blow up. If you try it and can’t see why it’s busted, contact me and we’ll noodle what’s going wrong.

6 responses on "In-line Text Editing with jQuery Tutorial" – Do share

Nice one, want more about jquery using. :)

rajesh kanna
Posted on April 15, 2008

Really it’s very help me for my project work….

[...] yet.) Everyone loves rounded corners, but the strictly CSS method is cumbersome to say the least. As documented I love jQuery, and I had been using the corners plugin for a while (the main one, that comes up in a Google [...]

Alec
Posted on July 29, 2008

This is very, very nice but I would recommend that you use nicedit (nicedit.com) for the text editing (look at their demos) and use this javascript for the updating of the content.

Hi gabe…nice and sweet tutorial….but you’ve reloaded the whole document at last…avoiding which could have been better approach…isn’t it ?

haven’t been here for a long time though…

i am too, solve this problem but not use jquery

this code dont use CSS and dynamicly create TextEdit after element , and after edited delete TextEdit

and works ENTER_event in TextEdit

works on Fx IE Opera

=======JAVASCRIPT=============================================
function insertAfter(newElement,targetElement)
{
var parent = targetElement.parentNode;
if(parent.lastchild == targetElement)
{
return parent.appendChild(newElement);
}
else
{
return parent.insertBefore(newElement, targetElement.nextSibling);
}
}

function editWord(obj)
{
obj.style.display = ‘none’ ;

var newInput = document.createElement(”input”);
newInput.id = “newInput” ;

if (navigator.appName.indexOf(”Microsoft”) != -1 )
{
newInput.onblur = function(){loseFocus(this)};
newInput.onkeydown = function(){return PressKey(event , this)};
}
else
{
newInput.setAttribute(”onkeydown” , “return PressKey(event , this)” );
newInput.setAttribute ( “onblur” , “loseFocus(this)” );
}

edit = insertAfter(newInput , obj);
edit.value = obj.innerHTML;
edit.size = obj.innerHTML.length*1.4 + 5;
edit.focus();
}
function loseFocus(obj)
{
obj.style.display = ‘none’ ;
var tt = obj.previousSibling;

if (obj.value == “”)
{
tt.innerHTML = “empty”;
tt.style.display = ‘inline’;
}
else
{
tt.innerHTML = obj.value + ” “;
tt.style.display = ‘inline’;
}

obj.parentNode.removeChild(obj);
}

function PressKey(e , obj)
{
var keynum;
var keychar;
var numcheck;

if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}

if(keynum == 13)
{
obj.blur();
}
else
{
obj.size = obj.value.length*1.4 + 5 ;
}

numcheck = /\d/;
return !numcheck.test(keychar);
}

=================================================

==========HTML===========================
Some text edit , please DOUBLE CLICK on this text
===========================================

Leave a comment