Making users click through multiple pages just to edit a field is so 1999. In this tutorial, you'll learn how to create an in-place editing system as found on popular sites, such as Flickr.
A word from the Author
With all the buzz around Web 2.0, ease of use is now much more important than ever. Being able to edit some content without having to go to another page is something a lot of users really crave. A lot of big names are already using this pattern to great effect. If you've used Flickr, you've probably seen this in action.
I believe a demo is worth a thousand words. Hit the demo and try it out yourselves.
Today, we are going to look at how to implement this with, you guessed it right, our favorite JavaScript library, jQuery. Interested? Let's get started right away!
Design Goals
Before we start looking at how to implement the functionality, here are a few thoughts about the goals and the resulting decisions.
- We need to let the user edit the content without leaving the page. This is a given.
- This should either function as a whole or fail as a whole. When JS is disabled, we don't want to run into weird quirks.
- The user should know the content is editable. A subtle blue background change should draw the user's attention to this.
- When dealing with how to trigger the edit there are a few options. We can either let the user edit on a normal click or double click. I've chosen double click since random double clicks occur at a smaller rate than random clicks. Switching it is just a matter of changing the parameter in the bind event.
- A way for the user to save or discard the edits.
- Save or edit events can be triggered by 2 ways. Keyboard events or mouse events. I chose mouse events since keyboard events lack specificity.
- With respect to mouse events, you could use either traditional buttons or usual links. I chose links for no particular reason.
- The user should be able to resume editing even if he clicks outside of the input box or leaves the page and comes back.
- Additionally, the user should be able to edit as many fields as possible simultaneously.
Now that we've mapped out our needs we can now move on to how we are going to do this.
Plan of Action
We'll now need to map out what needs to be done in a specific order.
Step 1: We'll need to add a class of editable to each elements which need this functionality.
Step 2: We'll next need to add hovers to each editable item to draw attention to the fact that that item's content is editable. We'll add and remove the hovers using JavaScript instead of CSS. This is mainly done for devices or browsers with JavaScript disabled. We don't want to send them wrong visual cues.
Step 3: When an editable item is double clicked, we need to swap out the contents and replace it with a text box with the old text in it.
Step 4a: When the user wants to save the edits, copy the input's value to the parent element and remove the input box.
Step 4b: Or when the user wants to discard the changes, replace the old content and remove the input box.
These are the basic steps in creating this functionality. Of course there are few other small things but I'll explain them as we go along.Core Markup
The HTML markup of the demo page looks like so.
<!DOCTYPE html> <html lang="en-GB"> <head> <title>In-place editing system - by Siddharth for NetTuts</title> <link type="text/css" href="css/style.css" rel="stylesheet" /> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/mojo.js"></script> </head> <body> <div id="container"> <h1>In-place editing</h1> <div>by Siddharth for the lovely folks at Net Tuts</div> <p>Elements with a class of <em>editable</em> are, well, editable. In case you haven't noticed, all elements containing the <em>editable</em> class get a blue background on hover to indicate this capability. </p> <p>Double click to edit the contents. Use the dynamically created links to save or discard the changes. You can open up as many fields to edit as you want without any hiccups.</p> <div class="block"> <h2>I </h2> <ul> <li class="editable">am Siddharth</li> <li class="editable">love working with the web</li> <li class="editable">am a freelancer</li> <li class="editable">write for Net Tuts</li> <li class="editable">can be found at <a href="http://www.ssiddharth.com">www.ssiddharth.com</a></li> <li class="editable">will never let you down or give you up :)</li> </ul> </div> <div class="block"> <h2>Things to do this week</h2> <ul> <li class="editable">Get design approval from Deacon</li> <li class="editable">Send an invoice to Albert </li> <li class="editable">Start work on Dwight's project</li> <li class="editable">Talk with Sarah about new ideas</li> <li class="editable">Check Seth's site for rendering bugs</li> <li class="editable">Meet with Clintson to discuss project</li> </ul> </div> </div> </body> </html>
As you see, disregarding the boiler plate, we have two unordered lists. Each li element has a class of editable to denote that its content can be edited.
We've also included the jQuery library and our own script file.
CSS Styling
body{
font-family: "Lucida Grande", "Verdana", sans-serif;
font-size: 12px;
}
a{
color: #000;
}
a:hover{
text-decoration: none;
}
p{
margin: 30px 0 10px 0;
}
h1{
font-size: 30px;
padding: 0;
margin: 0;
}
h2{
font-size: 20px;
}
#container{
width: 820px;
margin-left: auto;
margin-right: auto;
padding: 50px 0 0 0;
}
.editHover{
background-color: #E8F3FF;
}
.editBox{
width: 326px;
min-height: 20px;
padding: 10px 15px;
background-color: #fff;
border: 2px solid #E8F3FF;
}
ul{
list-style: none;
}
li{
width: 330px;
min-height: 20px;
padding: 10px 15px;
margin: 5px;
}
li.noPad{
padding: 0;
width: 360px;
}
form{
width: 100%;
}
.btnSave, .btnCancel{
padding: 6px 30px 6px 75px;
}
.block{
float: left;
margin: 20px 0;
}
Nothing special here. Just a bunch of code for layout and styling purposes.
Take special note of the editHover and noPad classes. We'll be using them in a bit.
JavaScript Implementation
Now that we have a solid framework and some basic styling in place, we can start coding up the required functionality. Do note that we make extensive use of jQuery. Specifically we'll need at least version 1.3 or higher. Anything less and it won't work.
Adding Hovers
As noted earlier, we'll need to add a subtle blue background to editable objects to signify they are editable. We've already created the editHover class to take care of this.
$(".editable").hover(
function()
{
$(this).addClass("editHover");
},
function()
{
$(this).removeClass("editHover");
}
);
This tiny snippet takes care of that for us. We use jQuery's hover method to add the editHover class when the element is hovered upon and remove it when it is not. We use this to refer to the specific element that is hovered over. If we had used .editable as the selector instead each and every element will get the class added to it. So we use this to target only the element we need.
Switching out the Elements
First up, we need to make sure our code is executed when the target element is double clicked. So we'll first hook up the handler for this event first.
$(".editable").bind("dblclick", replaceHTML);
We attach the replaceHTML function to the double click event relative to the editable element with that one liner. Now we can move on the switching out the elements.
function replaceHTML()
{
oldText = $(this).html()
.replace(/"/g, """);
$(this).html("")
.html("<form><input type=\"text\" class=\"editBox\"
value=\"" + oldText + "\" /> </form><a href=\"#\" class=\"btnSave\">Save changes</a>
<a href=\"#\" class=\"btnDiscard\">Discard changes</a>");
}
Let's go over our code bit by tiny bit.
I define the functionality inside a separate named function instead of an anonymous function for a specific reason: I'll be using this function more than once. Next, we save the content of the element for future use using jQuery's html method and replacing all quotes since it messes up our output down the line.
Now that our content is safely stored for later use, we can switch out the elements. First we empty out the li element by sending in an empty string to the html method. Next, we insert some standard HTML for an input box. We add some classes to it for styling purposes. More importantly, we set its value attribute to the original text contained by the element stored in oldText. We also add a couple of links to take care of saving and discarding the edits. We've also added classes to them so they can be targeted easily and for styling.
As always, we use this to target the element which triggered the event.
Keeping the Edits
$(".btnSave").live("click",
function()
{
newText = $(this).siblings("form")
.children(".editBox")
.val().replace(/"/g, """);
$(this).parent()
.html(newText);
}
);
First up, let me introduce jQuery's live method. You probably haven't seen this much before so I'll give a quick introduction.
You can't hook up handlers to events triggered by elements which are not even present in the DOM when the page and the JavaScript was loaded. If you use normal event binding functions, it'll fail due to the above mentioned reason. The live method takes care of that.
It binds handlers to events irrespective of when the element was created. For more about this, you can go through the official docs.
Lets look into our code now. We first bind the code contained within our anonymous function to the click event. Inside the function we first save the text contained in the input box. This can be a little tricky since the input box doesn't have an ID. So we first look for the form element which happens to be its sibling and then traverse through to find the input element. We then copy its value after replacing all the quotes it may contain.
Next, we obtain the links parent element, the li element and replace its HTML content with the text we copied in the previous step.
This block could have easily been created as a one liner but I chose to split it to 2 lines in the interest of readability.
Discarding the Edits
$(".btnDiscard").live("click",
function()
{
$(this).parent()
.html(oldText);
}
);
This is just as simple as it looks. Since the user doesn't want to keep any of the edits. We just replace the HTML content of parent element with the original text we had copied earlier to the oldText variable.
With this the core of our work is done. We just need to do a couple of edits to make sure things don't break when the user does unexpected things.
Binding and Unbinding
If you've tested out our code at this point you'll probably end up with this functionality breaking bug: When a user double clicks in the resulting input box it is now filled with the HTML content of the editing system. Try it yourself. With each double click, the value of the input box reflects by adding another bunch of text to it. This issue will probably be a lot worse if you've chosen click as the trigger event.
To rectify this, we need to unbind the event handler for that specific element alone and rebind them as soon as the user clicks either save or discard. Let's implement that now.
Our previous blocks of code now need to be edited out to so:
function replaceHTML()
{
//Code
$(this).html("")
// Earlier form insertion code
.unbind('dblclick', replaceHTML);
}
We unhook the handler for the element which triggered the event. The rest of the elements with the editable class still have their handlers intact and will respond to events.
$(".btnSave").live("click",
function()
{
// Earlier code
$(this).parent()
.html(newText)
.bind("dblclick", replaceHTML);
}
);
$(".btnDiscard").live("click",
function()
{
$(this).parent()
.html(oldText)
.bind("dblclick", replaceHTML);
}
);
Next we attach those handlers back in spite of whether the user chooses to edit them or not. If we don't re-attach these, the fields can be edited only once. The second time they are double clicked, the handlers are no longer attached to the events. We rectify this by hooking the handlers back to the events.
A Few Tweaks
This last bit of code is purely to spruce up the appearance of our effect. If you've noticed, the li has a bit of padding in place to make the text within look better. But when the text is stripped out and replaced by a text box we result looks ugly and breaks the effect. We want the text box to take up exactly the same space the original text took. With this in mind, we add a noPad class to the element when it has been double clicked and removed again when the user saves or discards the edit.
function replaceHTML()
{
//Code
$(this).addClass("noPad")
.html("")
// Earlier code
}
We unhook the handler for the element which triggered the event. The rest of the elements with the editable class still have their handlers intact and will respond to events.
$(".btnSave").live("click",
function()
{
// Earlier code
$(this).parent()
.removeClass("noPad")
// Earlier code
}
);
$(".btnDiscard").live("click",
function()
{
$(this).parent()
.removeClass("noPad")
// Earlier code
}
);
The Complete Code
Here is how the complete code looks like:
$(document).ready(function()
{
var oldText, newText;
$(".editable").hover(
function()
{
$(this).addClass("editHover");
},
function()
{
$(this).removeClass("editHover");
}
);
$(".editable").bind("dblclick", replaceHTML);
$(".btnSave").live("click",
function()
{
newText = $(this).siblings("form")
.children(".editBox")
.val().replace(/"/g, """);
$(this).parent()
.html(newText)
.removeClass("noPad")
.bind("dblclick", replaceHTML);
}
);
$(".btnDiscard").live("click",
function()
{
$(this).parent()
.html(oldText)
.removeClass("noPad")
.bind("dblclick", replaceHTML);
}
);
function replaceHTML()
{
oldText = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("")
.html("<form><input type=\"text\" class=\"editBox\"
value=\"" + oldText + "\" /> </form><a href=\"#\" class=\"btnSave\">Save changes</a>
.unbind('dblclick', replaceHTML);
}
}
);
Not bad. Fifty odd lines to add some spiffy new functionality.
Taking it One Step Further: The Backend
In the interest of not making it too long, I've stuck to creating the client side functionality alone. If you want to implement this functionality within your own projects, its implicitly assumed that you'd need a back-end system in place to save these changes and more importantly, you'd need an AJAX request for making this call asynchronously.
Adding this functionality should be a cinch but do make a note of this. The code above was created just to illustrate this pattern and not for production use. So I've abstained from adding additional IDs attributes to elements and name attributes to text boxes. In your production code, do add all of them so the text box's name attribute can be set meaningfully and in such a way the back end can recognize which piece of data needs to be updated.
To add an AJAX request, our save handler would have to be updated to so:
$(".btnSave").live("click",
function()
{
newText = $(this).siblings("form")
.children(".editBox")
.val().replace(/"/g, """);
$.ajax({
type: "POST",
url: "handler.php",
data: newText,
success: function(msg){
// Some code here to reflect a successful edit;
}
});
$(this).parent()
.html(newText)
.removeClass("noPad")
.bind("dblclick", replaceHTML);
}
);
Remember, for the back-end to make any sense of what you are sending to it, you need some additional data along with the updated text so the app knows which data to edit. You could easily send in more than one piece of data to the script if you need to.
Conclusion
And there you have it; how to add a user friendly functionality to your projects. Hopefully you've found this tutorial interesting and this has been useful to you. Feel free to reuse this code elsewhere in your projects and chime in here if you are running into difficulties.
Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.












User Comments
( ADD YOURS )enatom September 22nd
great. its like http://www.massbase.com
( )Benjamin Reid September 22nd
It’s like posting first to plug your site/portfolio? No, I don’t think it is.
( )enatom September 22nd
you’re clever, someone give him a badge.
GK September 22nd
Yeh sorry dude first posting like that is lame.. kinda like the website you also promote..
( )Jay September 22nd
You should’ve posted it further down, then fewer people would laugh at how crappy it is.
( )enatom September 23rd
yeahs becuase people actually “laugh” at a crap website ? either your too much of a nerd or your a looser.
annoyed September 26th
Yes people do laugh at crappy websites, especially when trying to view tutorials you get messages like “You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-15,15′ at line 1″
Perhaps you should learn to spell before insulting people. “YOUR” indicates possession – ie YOUR post is lacking in correct spelling and grammar, i believe you were after You’re – which means You Are.
Also, looser means to make something less tight. I believe you wanted to say “loser”.
Go and work on your website, and then come back and flame
Brian September 23rd
cool dot.
( )li9ht September 23rd
Lame.. “L”
( )NetChaos September 22nd
I really wish to have a feature like this in buddypress, so users wont have to go to the backend to make changes like editing profile.
( )Chad September 22nd
This is pretty awesome. It would be nice to see an extension of this where you are actually updating the content and storying it in database. Basically building out functionality for a live run-time CMS.
( )Nick Brown September 22nd
I did something like that here:
http://nickbrowndesign.com/port/beerInv/
It uses a prototype version of this same concept. There are no “discard changes / save changes” when you are editing, you just click outside the box when you are done editing and it submits to the database. You can check out the ajax calls to the DB with firebug if you are so inclined.
( )Dustin September 22nd
This shouldn’t be all that diifficult to update the new values in a database, since there is a form being used, you could essentially utilize some of that fancy AJAX magic playdoh
*cough* ajaxForm *cough*
( )Ming September 22nd
Great Tutorial! Well written.
( )LuK September 22nd
Very nice… always wanted to know how those scripts work =)… I like unify (from unit) very much, this is the king of the inline editors as far as I know them… editease was around very early and massbase I don’t know…have to check it out!
thx for the tutorial
( )Max September 22nd
You’re jquery looks so much nicer than mine haha. Great job I loved the tutorial
( )deepleap September 22nd
Wow this is exactly what I need! Thanks a thousand times!
( )Deoxys September 22nd
The demo is very buggy and doesn’t work as it should, but the tutorial is quite an inspiration though. THX
( )Matt September 22nd
Good information. I’ve been looking for something like jQuery’s .live() method for a month now to fix a bug in a project I’ve had on the back burner. One of these days I’ll have to work my way through the documentation in a more systematic manner, I guess!
( )David Ferguson September 22nd
Yeah, hate to nitpick but the demo needs some tweaking. There seems to be an error when saving or discarding changes. When you save or discard, either adds extra characters or lines in the content. It may be coming from the popup? that you are using. It shows a span within the content. Really show be fixed.
( )Siddharth September 22nd
Which browser are you using? I just checked it in FireFox, Opera and Chrome and it seemed to work without any quirky errors.
( )digikzes September 22nd
awesome tutorial.. keep it coming !!
( )Rhonda September 22nd
This bug can be replicated in Firefox. Edit “Start work on Dwight’s project” then without closing it, edit “Talk with Sarah about new ideas.” Now discard changes to “Start work on Dwight’s project.” It will be replaced with “Talk with Sarah about new ideas.”
( )Siddharth September 23rd
Duly noted. Thanks for the heads up.
( )wes September 22nd
Very nice, love these ajax/jquery tuts
( )Juan C Rois September 22nd
Thanks for this tutorial Siddharth.
It’s very well written and easy to understand, I love to use this in some of the CMS that I have to create for my sites.
Thanks and keep up the good work.
( )Joe Critchley September 22nd
“You can’t hook up handlers to events triggered by elements which are not even present in the DOM when the page and the JavaScript was loaded.”
… not exactly. Normal event bindings work for the state of the DOM when they’re binded. You can dynamically create an element, then binding an event. It’s just that it won’t pick-up new elements afterwards, unlike live bindings.
( )Siddharth September 22nd
You are right. I just didn’t want to get too technical.
( )Jeroen September 22nd
can you make it so clicking outside the edit area saves the field and closes the edit box automatically?
( )Boba September 22nd
Nice idea, and can be done easily.
$(document).click(function(){
$(’.btnSave’).each(function(){
newText = $(this).siblings(”form”)
.children(”.editBox”)
.val().replace(/”/g, “”");
$.ajax({
type: “POST”,
url: “handler.php”,
data: newText,
success: function(msg){
// Some code here to reflect a successful edit;
}
});
$(this).parent()
.html(newText)
.removeClass(”noPad”)
.bind(”dblclick”, replaceHTML);
});
});
Didn’t test it, so don’t take it for granted.
( )Boba September 22nd
The selector should be different. It’s a bit trickier, maybe he should update the tutorial.
Siddharth September 23rd
You could but then you’d have to close every open editable item to proceed. I didn’t want that.
This is just a template created to demonstrate the core pattern. Feel free to tailor it to your requirements.
( )Moksha September 22nd
its nice, hope to see some C# tutorial.
( )Socialcouch September 22nd
Joomla front end editing was a Google summer of code project by a guy i know. It was pretty similar but on a larger scale.
Nice heads up! I am gonna try doing this
( )Mike McLin September 22nd
(Referring to the Demo) In Firefox 3, if you double-click several fields, and then discard the changes for each, all of them will be saved with the first field you discarded’s value. http://screencast.com/t/5aVaHnQeYpio
( )Waheed Akhtar September 22nd
Hmm….nice tutorial buddy.
( )Tom Malaher September 22nd
Two bugs/misfeatures (using Windows/FF 3.0.10)
1) Open two items for editing. Make changes to both. Discard second one opened, discard first one opened. Result: “old text” from second will replace text of first, because a global was used to save the old value. This should be saved in a per-item hash or as a custom attribute of the DOM element or something.
2) my browser history gets an added history item for each text item I edit. I.e. to get back to the main page after editing several text items I have to hit “back” multiple times…
( )Siddharth September 23rd
1 is my fault. I just wanted to show the effect in demo and didn’t plan for multiple edits.
2, I’ll have to look into it.
( )Editable Div in jQuery September 22nd
Thanks.
( )A similar Tutorial to create Inline Editing in jQuery.
In line Editable DIV using jQuery
David Rojas September 22nd
Looking at the code, there seems to be a bug, the var oldText is global, if you edit one item, write something but don’t save or cancel it, and then edit another item, canceling the second item will save in it the default text of the first item. Try it and you’ll see what I’m saying. Good tutorial anyway.
( )Dan September 22nd
I noticed the same thing…
( )S Y September 22nd
Hay! Great tutorial!
( )Reminds me of the one Jeffrey Way did a while back on his photo gallery.
It’d be good to get the PHP working in the demo too.
Kevin Z September 22nd
Would love to see a back end to this. I know you went a bit into this, but AJAX requests linked up behind maybe a password (as to limit the site owner to make changes) would make a great cms.
Anyway, thanks for the tutorial, its great!
( )IgnacioRV September 22nd
Thanks Siddharth! this is a very useful tool when it comes to elements with tags or attributes that users will want to edit.
As for the oldText variable problem mentioned by David up here, maybe in the replaceHTML() function you can unbind the dbclick event to all the li elements instead of only to the one li which triggered the function (of course you will have to re-bind the event later…).
( )The problem here appears when there are a lot of “editable” elements in the page…
Siddharth September 22nd
If we unbind the event then we lose the ability to edit other items when an editable item is opened which I didn’t want. You could probably make all the changes you mentioned in a jiffy though.
It’s 12 am here and am sleepy which probably explains why I can’t seem to replicate the bug David pointed out. I changed the text of a field, didn’t save or discard the edit, opened up another, changed its value and then discarded the second’s changes. It worked normally for me. I’ll look into it when I wake up.
Thanks for the kind words, guys.
( )David Rojas September 22nd
OK, dobleclick first item, don’t save or discard just leave it in editing mode, now dobleclick second item, save or discard second item and finally discard first item. That way in the first item you’ll have the old value of second item.
Dave September 22nd
Easy way to duplicate it
Visit demo, double click every box to change them all to edit
Then, from the bottom up, skipping the very bottom, click discard changes.
You will see the very bottom’s default text copied into all of the fields above as you discard
Siddharth September 22nd
Duly noted. I can replicate it now. Sleep deprivation sucks.
I’ll see if I can get a patch up.
Thanks for the heads up, David. Much appreciated.
Rahul September 22nd
Good Catch David
IgnacioRV September 23rd
@Siddharth: yeah, it’s kinda difficult if you don’t want to lose the ability to open more than an editable item…
For now, I could think of two possible solutions… adding an array to the javascript to store the different contents of every opened item (client-side). Or don’t store the old value of the field… if the user click cancel just make an ajax request and load the original content again.
In both cases, will be needed identifiers for every “li” item… which results in increasing the complexity of the script.
I’ll appreciate you tell me if you find a good solution to this… I’m very interested and curious xD
(for the record: the jeditable plugin for jQuery mentioned down here automaticly closes the previous opened item before letting you edit the next one)
Siddharth September 23rd
Off the top of my head, the easiest way would be to create a hidden text box inside the li element and use that as the buffer instead of holding the value in a global variable.
IgnacioRV September 23rd
There’s always something new to learn
Thanks for the idea!
Siddharth September 24th
Glad you found it interesting.
Andrew E. September 22nd
Is there any way to get tabbing to work? What about pressing Enter when you are done editing a field to save the contents of the field, instead of submitting the form?
Or perhaps using enter to start editing a field once you tab over it.
Just a thought.
( )Siddharth September 24th
You could implement all of this in a jiffy. This article touched on the basics of the pattern and to that effect doesn’t include a lot of features. This is just a bunch of code to get you started.
( )Nick September 22nd
Lol designer code… This declares the oldText as a global variable, so if you click one editable then another and discard changes on the first it’ll be set to the second ones text. One possible solution would be to bind a function on save with the parameters being the oldText.
( )Siddharth September 23rd
I tried to make it so the demo wasn’t any more complicated than it had to be. Obviously I limited myself to a normal usage scenario in the interest of length. I prefer the phrase “absolutely as basic as it needs to be code” rather than “designer code”.
Thanks for the comment.
( )Mesothelioma September 22nd
Great tutorial. Thanks for the help.
( )Jay September 22nd
I didn’t create it, but a while back I found a script called ‘editEase’
It’s basically the technique demonstrated in this article, developed into a CMS for small static sites. I use it quite often!
http://code.google.com/p/editease/
( )Shaun C. September 22nd
This is amazing! Thank you for pulling me out of 1999, this is the technique I’ve been wanting to learn for quite some time.
Great work.
( )Diego SA September 22nd
Incredible! Simple, useful, amazing! Thanks a lot!
( )Gerd September 22nd
“Making users click through multiple pages just to edit a field is so 1999″
double clicks are 1999 too… doesnt work on an iPhone… ^^
( )Siddharth September 23rd
Sure but the user doesn’t have to leave the page which is the entire point of this tutorial.
( )Nick Brown September 22nd
Great, I’ve been using a Prototype version of this for a while now. However, I prefer to use jQuery when I can, and this one is definitely more elegant.
Still, if anyone is interested in the Prototype version, it’s here:
http://www.yvoschaap.com/index.php/weblog/ajax_inline_instant_update_text_20/
( )nate September 22nd
could you explain the backend more? How would you send name and id’s to the system?
( )Carina September 22nd
i’m not that knowledgeable when it comes to coding like this but had a question… you can update the fields just by double clicking… how does that prevent anyone from messing the whole thing up? meaning differentiate from who is actually able to make the changes are who isn’t.
( )Siddharth September 23rd
You’d have to collaborate with the back-end to ensure that only someone out proper authorization can edit the data.
( )Michael September 22nd
Now someone could do a little integration with CodeIgniter; Hint Hint!
( )jmb September 22nd
Awesome tutorial ! I love it.
small typo though btnCancel vs btnDiscard… :
in the css:
.btnSave, .btnCancel{
padding: 6px 30px 6px 75px;
}
in the js:
( ).html(” Save changes Discard changes“)
jmb September 22nd
Moderator: please discard my previous post… I’m trying to paste some of the original code :
class=”btnDiscard” > Discard changes
( )jmb September 22nd
huh.
( )how about this.
Discard changes”)
iPad September 22nd
This is perfect for a CMS! Dude you’re awesome!
( )Carl - Web Courses Bangkok September 23rd
Very useful for our programming course, thanks!
( )Martyn September 23rd
Yet another awesome tutorial from Nettuts and Siddharth, Thanks very much!
( )Ivan Mišić September 23rd
Great tutorial, thx for share
( )jarobe14 September 23rd
For those not sure about implementing the back-end, hear are some changes you’ll need to make to get you started:
1) Change:
( )Sreeram September 23rd
Nice tutorial !! Will be helpful for the next project
( )jarobe September 23rd
(ignore my above post -> was pretending to be dumb)
For those not sure about implementing the back-end, here are some changes you’ll need to make to get you started:
currentId = $(this).parent().attr(”id”); // <- Add this line
$.ajax({
type: "POST",
url: "handler.php",
data: "text="+newText+"&id=" + currentId, // <- Change this line
success: function(msg){
alert(msg);
// Some code here to reflect a successful edit;
}
});
Important: Of course you will need to add id’s to each element
You can now use PHP $_POST['text'] and $_POST['id'] to insert/update the correct DB column with the new data.
Hope this helps!
jarobe
( )Marcus September 23rd
There is actually a plugin for this in jQuery called Jeditable which has been around for a very long time and is update regularly.
( )Siddharth September 24th
I am aware. I am merely trying to deconstruct such an effect here.
( )DemoGeek September 23rd
Siddharth – Another easy to understand write-up from you…live method is something totally new to me and it makes sense to have it isolated with the other methods that can work only on the initial/original DOM tree…looking forward to the next one.
( )Siddharth October 27th
Really glad you liked it.
( )Win! September 23rd
Hey there, I was wondering, what happens if we have more then one line of text to edit?
What happens if there was a whole paragraph??
Can you make it so it edits in a text area please? Ta
Great tutorial btw man.
( )Siddharth September 24th
You could just replace the text box in the code with a text area.
( )Win! September 25th
Tried that mate, but it didn’t work
All the textarea contained was the code for the submit and cancel editing links
Siddharth October 27th
Maybe I could take a look at the code?
Dan September 23rd
Interesting tutorial but it becomes very useless when it comes to a dynamically driven website say by PHP and ColdFusion pulling databased records for users
( )Siddharth September 23rd
Why? Flickr has been using such a system for ages now.
( )ken September 23rd
oaw ! has a bug ! when i’m double click to any text, next step, i’m double click to text other, bug is display the same text in input tag
the oldText var current is a text first double click !
( )ken September 23rd
fix the bug if text has ” char, in the
( )$(”.btnDiscard”).live(”click”, function(){
$(this).parent().html(oldText).removeClass(”noPad”).bind(”dblclick”, replaceHTML);
});
edit this to
$(”.btnDiscard”).live(”click”, function(){
$(this).parent().html(oldText.replace(/"/g, ‘”‘)).removeClass(”noPad”).bind(”dblclick”, replaceHTML);
});
Web 2.0 September 24th
Interesting tutorials, thanks for sharing
( )Kyle September 24th
Why are you using JavaScript to add the `editHover` class?
You can simply use `.editable:hover { }` in your CSS, unless I missed something…
( )Siddharth September 24th
Simple answer: control. I don’t want random effects to kick in when a user has JS disabled but has CSS enabled. This way, either it works as a whole or fails, gracefully, as a whole.
( )Kyle September 24th
Gotcha. Makes sense.
Morgan Cheng September 24th
Awesome tutorial!!!
Can you explain why to replace quotes?
$(this).html().replace(/”/g, “”");
Above code seems not working. I just change it to replace(/”/g, “”) to remove quotes. But, I don’t understand why should tweak about quotes.
And, there is a bug. The repro steps are:
( )1) double click to edit one item;
2) double click to edit another item;
3) discard on the first item.
We can see the text of 2nd item is saved to first item. This is because we have a global “oldText” variable.
Siddharth October 27th
I am aware of the bug. Thanks for pointing it out.
I replace the quotes because it messes up the script if someone enters HTML in the textbox.
( )Zilus October 19th
Is there a way to use a MySQL query after editing?
( )Siddharth October 27th
Well, yeah. It just isn’t covered in this tut. Feel free to expand on this base.
( )Prabodh October 24th
Nice Tutorial..
( )But it enables me to open multiple inlines to edit which leads to wrong updates..
…we need to lock others once we open a particular line to edit…
hope you got what i meant..can you clarify that
Siddharth October 27th
Enabling you to open multiple fields was a feature I wanted to implement. As others have noted above, it was a bug on my end which makes you lose edits when more than one field is opened.
( )Siddharth October 27th
Gah. I used my work email.
( )