jQuery Inline Edit tutorial

Spanish translation by Maria Ramos.

A friend recently asked me to review his edit-in-place code which turned out to be a modification of the one found at http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax. Reading the tutorial on that page I asked myself how I would do this differently? Defining a global setClickable() function and then calling $('#editInPlace").click() is totally uncool, essentially limiting yourself to one edit-in-place area per page.

Since the concept of edit-in-place is so simple and the implementation should be likewise I want to try and tackle this as a tutorial by going through concepts and teaching to build from scratch.

The concept

There’s a piece of text on a page, e.g. a heading or paragraph, looking plain and un-interesting. When you hover over it however a visual highlight, usually pale yellow, indicates that it’s something special – an editable region. You then click on the text and it magically transforms into an editable box with save and cancel buttons tagged at the end. On clicking either save or cancel the editable box transforms back into its original form with text updated if saved.

The build

What we want to do is put these concepts into code whilst building something that’s re-usable. A plugin will do the trick! Let’s call our plugin inlineEdit.

We are only 3 steps away from achieving our goal! Follow along…

Step 1: Getting the basics right

The basic functionality consists of a static text element (span, div etc…) that can transforms into an input element on click. And on hover the text element will highlight to indicate special interactions.

Here’s our first pass: Basic Interaction

Code explanation: Our plugin accepts a CSS class name defined in a stylesheet which is used to toggle the text element’s classname – a class defining a background-color typically #ffC is sufficient for this. On clicking we replace the entire contents of the original text element with an input element and pass the original content into the input as its value. For now changes are saved when the input loses focus.

Step 2: Save, Cancel & Callbacks

As you may notice above we saved on blur and there is no way of canceling changes. Let’s improve the interaction by adding a save button. This is important as you’d want to do something with the changes or allow a user to manually cancel. Every application does something different at the saving stage so we’ll simply define a save callback and let the implementer decide what to do on save, be it Ajax post or what not. The save action is also cancelable by returning false inside the callback.

Here is our second pass: Save, cancel and callbacks

Step 3: Finishing Off

Our plugin is nearly there. Just a few nice finishing touches remaining. We want to give the user ability to change the button label and pass an initial value. Also to make the plugin more re-usable we want to move the core plugin code out to a separate file and reference it instead. To set the stage for further improvements in the future we also split the code into two distinct clauses.

Final result: Live Demo and source code is here

Usage

Now to use this brand spanking new plugin we simply apply it to any DOM element like so:

HTML

<span class="editable">Hello World!</span>

JavaScript – Basic

$(function() {
  $('.editable').inlineEdit();
});

JavaScript – Customised button label with save callback

$(function() {
  $('.editable').inlineEdit({
    buttonText: 'Add',
    save: function(e, data) {
      return confirm('Change name to '+ data.value +'?');
    }
  });
});

Feedback welcome – if you happen to improve upon this code base please share-a-like!

Enjoy!

Update 26-Aug-09: Added placeholder for cases when text is empty; changed label option to buttonText to minimise confusion.

Update 18-Oct-09 Fixed bug in setting initial value via script.

Update 17-Jan-10 Moved code to http://github.com/caphun/jquery.inlineedit. I will continue to improve this plugin from there. Feel free to fork it!

  • Javier

    I usually use Jeditable for this kind of things. I find it quite useful.

  • caphun

    @javier – Jeditable looks very good! Thanks for the link!

  • http://advomatic.com dalin

    I'm still getting a handle on jQuery syntax. Why

    $(function() { …

    and not

    $(document).ready(function() {…

    ?

  • caphun

    @dalin – One's a short form of the other, I'm just being lazy. ;)

  • http://nerdnotes.org Bram

    Hi CaPhun, I really like your inlineEdit plugin ;-) . It's much smaller and easier to use than jeditable! I do have one little problem tough, it's when the content to be edited is empty or cleared by the user. I'd like to have an alternative text which is not used in the input field when clicked. Although I think it can be solved with css, do you have a suggestion how to do this in inlineEdit?

    Thanks, Bram

  • caphun

    @bram – glad you like the plugin. :)

    Having a default text label is a good idea. There are several alternatives. If the editable region is blank we could replace it with a label element that disappears on click or make the input box sticky if no content is present. The latter being one less click.

  • http://nerdnotes.org Bram

    I've added the following lines near the bottom of the script:

    if (self.text().length == 0) {

    self.text(options.emptylabel);

    }

    And added an extra (empty) default option on top. It only sets the 'emptylabel' when the text is empty initially and doesn't cover the case when the text is cleared. It would be nice to add a css class whenever the 'emptylabel' is used, so that it can be styled accordingly.

    Cheers,

  • caphun

    @bram – I just added a placeholder option to deal with your situation. Now if the editable region is empty initially or made empty a placeholder will be added. The placeholder defaults to "Click to edit" but you could change it to something else via the placeholder option. There is also a class tagged onto this generated placeholder. Source code and demo updated.

  • http://nerdnotes.org Bram

    Thanks a million! I'll checkout your jquery-ui rewrite later.

  • calin

    how can be this combine with php to use a database?

  • calin

    do you have an example of the php file?

  • caphun

    sure:

    http://yelotofu.com/labs/jquery/snippets/inlineEd

    I'm using sessions to generate a unique experience – not recommended for production. You should replace with db read/write.

  • calin

    I played around with it but I want to make a change,

    by saving a number in that field

    if it starts with 1234 and I want to enter 4000 but I type by mistake 40a0 I receive an alert and then the field becomes again 1234 and does not remain open for input; can you give me a solution?

  • caphun

    @calin: I think that's by design. To save your change you will have to click on the "save" button. What alert are you getting? Could you post up a demo?

  • calin

    maybe I didn't explain very well

    I want to put in js a check for the input field to accept just numbers;

    function check_edit(myval) {

    var tn = myval;

    var tnPat = /^(0|([1-9](d{1,4})?))(.(d{1,2}))?$/;

    var tnArray = tn.match(tnPat);

    if (tnArray == null) {

    alert("the value is not a number !
    (99999.99)");

    return false;

    }

    }

    end then I have

    return check_edit(data.value);

    If I enter by mistake a letter, it shows the alert, but then the input field because didn't passed the check receives the initial value; I want to say that the field does not remain open for input, I must click again on the span to edit it again, and re-enter the value

    • caphun

      right, I see what you are saying. As return false is equivalent to moving focus away from the input it will cancel the edit. I will give this some thought. Maybe it's more intuitive for return false to simply cancel the save operation and maintain the state of the input box? That makes sense actually.

  • calin

    yes it makes sense;

    to complicate a little bit there are 2 cancels:

    - if you need a confirm and you abort the change, then you send a cancel, after that the input disappear

    - if you check the field for a desired value or type, and you receive an alert then you receive another cancel, which keeps the input

  • caphun

    @calin: Actually I would argue that it's just one. Even with the confirm dialog it should just go back to the input box if false is returned.

  • James

    Heya,

    Great plugin, I have a question tho – I want to use the jquery live event on it (http://docs.jquery.com/Events/live) so I can add elements e.g. list elements with editable fields as at the moment only the original elements are editable.

    I have tried replacing instances of bind with live however I just keep breaking it whatever I try. Any advice as to what I can do?

    Thanks

  • caphun

    @james: Thanks :) Could I see an example of what you're trying to do?

  • James

    This code is what i'm doing, just cut down somewhat. Basically select an 'example page' from the drop down list and it will add a list item to the test list. I have used the jquery .live so I can delete and move the added list items, but I can't seem to do this with the inline edit.

    Example Page 1

    Example Page 2

    Choose Page

    Example Page 3

    Example Page 4

    function buildString(elementID, count){

    var li_string = '

       ' + elementID + '

    function sortable(){

    $("#test-list").sortable({

    handle : '.handle',

    update : function () {

    var order = $('#test-list').sortable('serialize');

    counter = order.size();

    $("#info").load("process-sortable.php?"+order);

    }

    });

    $('#test-list li img.delete').live("click",function(){

    // Delete element

    });

    $('.editable').inlineEdit({

    buttonText: 'Add',

    save: function(e, data) {

    return confirm('Change name to '+ data.value +'?');

    }

    });

    $('#menu_select option.page').click(function(){

    $(this).remove();

    var counter = $('#test-list li').size() + 1;

    var select_val = this.value;

    $(buildString(select_val, counter)).appendTo('#test-list').hide().css('opacity', 0).slideDown('slow', function(){

    $(this).fadeTo("slow", 1);

    });

    i++;

    });

    }

    sortable();

    Thanks

    James

  • James

    Ooops the code got formatted weird, I'll try putting it in pre tags

    Example Page 1

    Example Page 2

    Choose Page

    Example Page 3

    Example Page 4

    function buildString(elementID, count){

    var li_string = '

       ' + elementID + '

    function sortable(){

    $("#test-list").sortable({

    handle : '.handle',

    update : function () {

    var order = $('#test-list').sortable('serialize');

    counter = order.size();

    $("#info").load("process-sortable.php?"+order);

    }

    });

    $('#test-list li img.delete').live("click",function(){

    // Delete element

    });

    $('.editable').inlineEdit({

    buttonText: 'Add',

    save: function(e, data) {

    return confirm('Change name to '+ data.value +'?');

    }

    });

    $('#menu_select option.page').click(function(){

    $(this).remove();

    var counter = $('#test-list li').size() + 1;

    var select_val = this.value;

    $(buildString(select_val, counter)).appendTo('#test-list').hide().css('opacity', 0).slideDown('slow', function(){

    $(this).fadeTo("slow", 1);

    });

    i++;

    });

    }

    sortable();

  • James

    Obviously not working, I hope you get the idea, I can email it if you want?

  • caphun

    @james: I should have mentioned jsbin.com eariler. Could you put it there? It would be easier for me to see what the code is doing.

  • James Lang
  • caphun

    Here's a possible solution:

    http://jsbin.com/ohuzo/edit

  • James

    That works perfectly, thanks so much.

    Sorry to bother you again, but I have another page with a similar issue i.e. html created after dom initiated and the inline edit not working. I tried what you did to get the last one to work but it doesnt seem to have sorted it.

    Any chance you could have a look? I am so sorry to trouble you again!

    http://jsbin.com/ifumi/edit

  • caphun

    All I did was move the inlineEdit call into the blur callback:

    http://jsbin.com/ufaju/edit

  • http://www.indialike.com indialike

    Very nice and useful tutorials to web designers,

    Thanks for posting.

  • tom

    Heloo caphun, i've tried your plugin and its work very well, but there is a problem, i wants to modified your plugin, i want to change the input style into a text area, but i got some error, i dont get a value of the new data

    else if ($this.is(self[0].tagName) || $this.hasClass('inlineEditText-placeholder')) {

    self

    .html(''+ self.value() +' '+ options.buttonText +'')

    .find('textarea')

    if i run this, there will appears a confirm box

    " Change name to undefined? "

    can you fix this ??? Thanks before (^_^)

  • caphun

    @tom: thanks :)

    Actually I have a version of this plugin that supports textarea. It might be slightly buggy but will put it up on github.com very soon.

  • caphun

    As promised I have moved this code to github.com

    http://github.com/caphun/jquery.inlineedit

    Feel free to fork it!

  • tom

    Wow, thanks a lot for your help, its work properly now. Many thanks from me.. (^_^)

  • kalyan

    Caphun,Great plugin and thank you for sharing. Your plugin is working for me except for one scenario where I was adding new row to the table through jquery. Inline edit is only working for old rows but not the new rows that were added through jquery. Can you please help me on this..

    I placed my code here..

    http://jsbin.com/anumi3/edit

  • kalyan

    Caphun,You already gave the solution for this.. http://jsbin.com/ohuzo/edit
    It worked for me too..Thank you

  • kalyan

    Caphun,Would I be able to capture/know the currently edited and saved id or name of the or or . at the function $('.editable').inlineEdit /

    Thanks

  • caphun

    Hello Kalyan. Thanks for the compliments. Yes, it's possible to know the currently edited element within the save callback by simply using "this". to get the id of the element use this[0].id, this[0] is the span element.

    As for your other questions here's a code snippet to demonstrate it working via re-binding:

    http://jsbin.com/okese3/edit

    Since jQuery 1.4 supports focus/blur through the focus(in|out) events I will switch to the .live() method soon.

  • amarushakur

    I really liked your example but i will like to apply some validation to the editable contents before they are saved. i want both a client side and php server side validation. if the validation fails, the edited contents should not be saved.

  • amarushakur

    my page uses a php script to display a table of records from a databse. i need help on inline editing such that when a user clicks on a row, the fields become editable and the edited contents are validated both at the client side and php server side before it is finally saved. Please help me. its my final year project. the server side script is jquery

  • caphun

    @amarushakur: It is certainly possible to validate the contents before submission. Take a look at my save example within demos here:

    http://github.com/caphun/jquery.inlineedit

    You can place client-side validation inside the save callback function.

    Hope that helps.

  • Chris

    Very nice. Is it possible to send a hidden ID field along with the updated text using ajax so that the correct database field is updated. I'm sure this is trivial but I am not getting it.

  • caphun

    @chris – yes just add another value to the ajax data object when saving, e.g.

    <code>

    $.ajax({

    data: {

    'action': 'save',

    'value': data.value,

    'id': 'my-hidden-id-value'

    }

    });

    </code>

  • Chris

    I guess while I'm at it, I need to be able to do this on a single row at a time in a table. The idea is to be able to take a numeric text field and modify it while submitting the results to the database with ajax. I can do this (sort of) but the id is returning the same for each row. It is just using the first id from the first row.

  • Chris

    This is what I have done in the js.

    var id = document.getElementById('holidayID');

    var html = $.ajax({

    data: { 'action': 'save', 'value': data.value, 'id': id.value }

  • caphun

    @chris – that won't work since the ID attribute is supposed to be unique. The entire HTML page should only have one holidayID. A better approach would be to look-up the closest container and grab the corresponding. If you put up a very minimal example script on http://jsbin.com I could give more specific advise.

  • jeffery

    hai, this seems to be a very good replacement for jeditable plugin…..but i need to apply validations for the editable fields…..is it posiible to do this here….

    cuz am not just getting it right to work with validations and edit together…

    can just show any sample codes of how to implement it…. it would be a great help….

  • Michael

    Hi,

    First I would like to thank you for a great script.

    I am having some difficulties with certain characters.

    You should be able to replicate the bug if you go to your demo (http://yelotofu.com/labs/jquery/snippets/inlineEdit/demo_final.html) and type a smiley, for example :) , and then click on save.

    When I do that I get:

    uncaught exception: Syntax error, unrecognized expression: :)

    Any ideas?

    Thanks!

  • jason

    in case anyone wants to use a textarea instead of input, just change to add control: 'textarea' in options.

    $(function() {

    $('.editable').inlineEdit({

    buttonText: 'Add', control: 'textarea',

    save: function(e, data) {

    return confirm('Change name to '+ data.value +'?');

    }

    });

    });

  • jason

    i am using .load() to load in results into a div, but this doesn't seem to work on those results. if i copy the same html i am outputting and place it directly in the page, it works fine. any ideas to what i may be doing wrong? thanks.

    • caphun

      @jason: don't fully understand what you're trying to do with .load() and .inlineEdit(). Could you put something on jsbin?

  • http://www.jeffrose.ca Jeff Rose

    Just curious if anyone knows why this would have issues with French characters? When I display certain French text on the page, I get an uncaught exception from Javascript and everything fails.

    Looking for suggestions. I can't share my actual page as it's in a corporate dev environment.

  • caphun

    @jeff: afaik, French characters should be supported. I could look into this if you put related code on jsbin.com that demonstrates this issue.

  • http://www.timandkathy.co.uk/journal/ Tim Beadle

    Hi,

    This is a great plugin, but only seems to work with mouse interaction (unless I'm missing something!).

    When the enter key is pressed while the input box is enabled, the whole form is submitted; if you tab to focus the "save" button, the edits are discarded because the input field lost focus.

    Any ideas for making this keyboard-friendly?

    Thanks,

    Tim

  • igor

    A little bug in plugin was found.

    … self.html('<input type="text" value="'+ self.value() +'…

    this code doesn't works if self.value() contains " (double quotation mark).

    Can be fixed using attr() method for setting input value:

    self.find('input').attr('value', self.value())

  • caphun

    @tim: you're completely correct. I'll look at making this keyboard-friendly!

    @igor: thanks for the bug report!

  • http://www.shaundunndesign.com Shaun

    Hi Caphun,

    First of all, great script. I had a biggie question though. I'm trying to figure out how to save for a table within mySQL database. I noticed you have the php version setup for a session and I guess I'm pretty novice when it comes to combining javascript and php together. Could you please help me out??

    I have like 5 different fields I want to change within my "USERS" table.

    1. Firstname

    2. Lastname

    3. Phone

    4. Email

    5. Website

    Regards,

    -Shaun

  • http://www.market-analyst.com Mathew

    Hi,

    Great script – helps a lot. I also needed to have key capture – Enter to save and Esc to quit. I added the following in the mutate function

    .find( self.options.control )

    .keyup( function( event ) {

    if (event.keyCode == '13') {

    self.save( self.element, event );

    self.change( self.element, event );

    } else if (event.keyCode == '27') {

    self.change( self.element, event );

    }

    })

    .end()

    Hope it helps.

    Oh and is there any reason why placeholders would not be set on load?

  • caphun

    @mathew: thanks for giving back! I added your change to the codebase, see:

    http://bit.ly/9yGqVV

  • http://www.theglobalgain.com Paul

    Hi, first great script. I like it and have started to build an grid around it. But i have ran into issues especially IE8.

    Even the basic example at the top of the page does not work in IE8.

    Mozilla Firefox works nicely. In IE8 using basic example if you click on "Joe Blogg" and start to type before "Joe" works good but if you start to type after "Joe Blogg" it does nothing then when u click to lose focus the text box stays there and cannot be changed. Please tell me there is a fix for this b/c i really like the script.

    Thanks in advance

  • http://www.theglobalgain.com Paul

    I figured out the issue with IE8. When the field is changed to a textbox the self.bind('click') event still gets called. I wrote a mod that will actually determine if the control contains text or a textbox before continuing on with the rest of the code in the click event. Hopes this helps someone else! thanks for the script

  • Dave

    First – love the simplicity of this.

    One issue I'm having though in IE7:

    When you clicked an editable element in IE7 the cursor goes to the beginning of the text. If I then click the mouse at the end of the text the textbox seems to lose focus so that when I click delete it actually acts as the browsers 'Back' button rather than delete a character. This actually happens if you click anywhere outside of the text box.

    I can never seem to get focus back to the text box unless I highlight the text or click save/cancel and start again.

    Has anyone else experienced this in IE7 with jQuery 1.4.2?

  • http://brettic.us Bretticus

    Hi Caphun,

    Thanks for publishing this script. I was looking for a minimal inplace editor, and this one seems pretty powerful. A bit too powerful for my limited javascript skills as luck would have it. I noticed that the only thing being sent to the save() function in data is the value of the input. While, that's great in a very simple case, it's not so helpful for using ajax as your save() function. What makes sense to me in this case, is setting the original id attribute to some property. That way, I can send that to my server-side script and actually know what I will be changing. I have tried getting the id in the init method and sending that from the save method. I always end up with a blank. Could you, perhaps, post a snippet here how to extend your plugin with the original element's id attribute value? Much appreciated.

  • http://brettic.us Bretticus

    Here is what I've tried:

    [sourcecode lang=""javascript""]

    // plugin defaults

    defaults: {

    hover: 'ui-state-hover',

    value: '',

    control_id: '',

    save: '',

    buttons: 'save cancel',

    placeholder: 'Click to edit',

    control: 'input'

    },[/sourcecode]

    [sourcecode lang=""javascript""]

    control_id: function( newValue ) {

    if ( arguments.length ) {

    this.element.data( 'control_id' + namespace, newValue );

    }

    return this.element.data( 'control_id' + namespace );

    },[/sourcecode]

    [sourcecode lang=""javascript""]

    save: function( elem, event ) {

    var hash = {

    value: this.element.find( this.options.control ).val(),

    id: this.element.attr('id')

    };

    if ( ( $.isFunction( this.options.save ) &amp;amp;&amp;amp; this.options.save.call( this, event, hash ) ) !== false || !this.options.save ) {

    this.value( hash.value );

    this.control_id( hash.id );

    }

    },

    [/sourcecode]

  • caphun

    @bretticus: Done some minor refactoring of the code and changed the save callback's <code>this</code> object to refer to the original DOM element. So now you should be able to get the id within the callback function using <code>this.id</code>, example: http://bit.ly/bKjZ4o

    All – I'll get round to testing IE soon. I promise!

  • caphun

    As promised, here's a commit with a load of IE fixes: http://bit.ly/dz6a6l

  • Nathan

    Thanks for a great plugin!

    Is it possible to use it to edit a row in a table as in multiple elements at once with one save for the whole row?

    Thanks

  • Gray

    Great plugin!!

    i was wondering is it possible to have a "double click " event call the inline editor instead of a single click?

    Thanks

  • Jay

    This is cool. Does the extensions example with the drop list actually work? I am getting odd behavior:

    1. the list won't stay dropped down on selection

    2. the value is not sent through on save (maybe because one can't click anything in the drop down?)

  • Jee

    Hi,

    cool plugin. As Gray asked – how could it be (is there a way) initialized by double click instead of the single click?

    thanks,

    Jee

  • caphun

    @nathan: the plugin doesn't handle this situation as it only acts on a single field.

    @gray & @jee: what's the rationale behind double rather than single click?

    @jay: the extensions example should work but maybe I've not tested it exhaustively enough. Could you send me a testcase?

  • Gray

    Hi Caphun,

    My rationale for the double click was that i have another single click event being used to multi-select some other elements within my page.

    I did find a way to get it to work. I noticed that you was binding the event with a single click so i changed it to a double click

    see jquery bind() http://api.jquery.com/bind

    $('.dblclick').inlineEdit();

    and added the class name of .dblclick to all the elements I'm calling the function on.

    (within jquery.inlineedit.js)

    on line 28 i changed:

    .live( ['click','mouseenter','mouseleave'].join(namespace+' '), function( event ) {

    to

    .live( ['dblclick'].join(namespace+' '), function( event ) {

    (did not need mouse functions)

    on line 36 i changed:

    case 'click':

    to

    case 'dblclick':

    and it works nicely.

    The only issue i now have is if i click away from the element once the inlineedit has been called, the element freezes and i can not get the focus back on the element. So i have to refresh the page, I'm still working on that issue but will post my results once i find the problem.

  • Gray

    found it,(you will have to forgive me I'm still learning jQuery)

    in line 83 i changed

    cancelOnBlur: false

    to

    cancelOnBlur: true

  • caphun

    @gray: I think a better approach to this on the plugin perspective would be to add a mutateEvent option which defaults to "click".

  • http://pickatutorial.com Computer Tutorials

    Good for beginners. I think jquery in its very nature is very easy to understand…

  • hazdrake

    Am using this, but I need one extra thing, I also need to have the old value of the field in some variable, I tried adding putting in code for getting the old value of the text field at the start of mutate but it didn't worked. Am new to jquery, a little help would be appreciated

  • Pingback: RealTime - Questions: "Help me please about javascript odd or even code please!!!!please!!!!?"

  • jack

    small update – added

    if (self.value() == this.options.placeholder)

    self.value('');

    to the mutate: function so that upon first entering edit mode the edit box is blanked out if no new text was entered.

  • jack

    Also modified the save: function to return more date (event, newValue, oldValue, element)

    this.options.save.call(this.element[0], event, hash, this.value(), elem ))

  • http://www.arronbailiss.com Arron Bailiss

    Awesome little plugin, thanks.

  • Scott

    Thanks for writing this.

  • Pingback: Buzz Lightyear is here » Blog Archive » links for 2011-03-04

  • http://none Wako

    Bug with Firefox 3.6.15 : jquery…edit.js (ligne 30)

    I haven't test on the other browser

    this.each(function () {$.inlineEdit.getInstance(this, options).initValue();}).live is not a function

    [Stopper sur une erreur] .live( ['click', 'mouseenter',…n(namespace+' '), function( event ) {

  • JFR

    Thanks for sharing.

    What if I want to revert back to the original value from an async ajax call?

    Example:

    [sourcecode language=""javascript""]

    $('.edit').inlineEdit({

    buttons: 'Ok',

    cancelOnBlur: true,

    save: function(event, data) {

    $.post(&quot;save.php&quot;, {id : $(this).closest('tr').attr('id'),

    value : data.value, colonne : $(this).index()},

    function(msg){

    if(msg !=='OK'){

    alert(&quot;Error&quot;);

    –&gt; revert back to initial value.

    }

    });

    }

    });

    [/sourcecode]

  • caphun

    @JFR: return false to revert on the save function.

    @jack: thanks reporting that bug with the placedholder value. Fixed in github. btw, you can also get those values without modifying the save method like so:

    [sourcecode language=""javascript""]

    $('.editable').inlineEdit({

    save: function(event, data) {

    var widget = $( this ).data('widget.inlineedit');

    // original element, old value, new value

    console.log( widget.element, widget.value(), data.value );

    }

    });

    [/sourcecode]

  • http://2helixtech.com Matthias

    Great script. Incredibly easy to use.

    I'm noticing what might be a bug with saving via Ajax. When you press the Enter key to save it sends the Ajax request twice. I'm using essentially the same script as your repository demo (https://github.com/caphun/jquery.inlineedit/blob/master/demos/save.html)

    • caphun

      @matthias: thanks for bug testing. I just tried this myself but couldn't reproduce the problem. could you upload a test? The demo does an Ajax post on page load to get the latest value then another on save.

  • Matthias

    @caphun It was only happening when I had the save button and hit enter – like enter was triggering the save button, but also called the keyup event in the code (without preventing default action).

    I've since removed the save button and everything works fine. I'll try extracting the inline edit specific code from my source and demo it by itself to see if it still does it.

  • newuser

    @caphun, can I do this with inlineEdit:
    - instead of placeholder text, have a textbox input (as usual, click to enter text)
    - instead of save button, have "enter" to save text
    - instead of cancel, have onblur to cancel changes

    Can I also pass additional variables other that the one inlineEdit text to be saved together with it?

    Thanks caphun!

    • caphun

      1) the inlineEdit always starts off as in-page text and mutates into a textbox onclick. To start off as a textbox you'd need to somehow trigger the mutate function onload. You could add a custom event to the live() call say 'init' and then trigger it like so: $('.editable').inlineEdit().trigger('init');

      2) Yes, use the buttons option with the following value: '<button class="save">enter</button>'

      3) Yes, set cancelOnBlur to true

  • jean-louis

    hi,
    it works great! how can i edit a multi-line field?
    thanks
    jl

    • caphun

      @jean-louis: see the textarea example

  • Andrew

    Is this plugin compatible with Jquery 1.6.1?

    • caphun

      @andrew: should be.

  • http://michaeljsalo.com Michael J Salo

    Thanks to the author for this slick and easy inline edit script. I'm using it in textarea mode and am running into one trouble. If a user enters line breaks into the textarea, after saving it shows up as an HTML break tag with the brackets escaped. Not the expected result. How might this be fixed.

  • Ken

    Is there a way to easily manipulate the style of the textarea or the input, the same way that I can modify css for the buttons?

    I thought about adding a class attribute to the input control which I could then manipulate with jquery .css(), but I don't want to mess with the .js file…

  • Pingback: Inline text change not updating on ajax request (but changes on DB) - Programmers Goodies

  • Cman

    Any examples using the plugin with classic asp?

  • Ronny

    Hi caphun! Very cool plugin, and as a newbie to jQuery, I found it very clean and simple to use :-)

    On question:
    Is it possible to trigger the function from another node than the one with class="editable". I would like to use a trigger e.g. <a class="triggerEditable">

    Something like this:

    <span class="editable">The Text</span>
    <a class="triggerEditable">Click to edit "The Text"

    Anyone?

  • http://www.infyways.com/ Mark William

    Nice post. Very very important tutorial.
    Thanks for sharing. Mark

  • http://www.hapjesmaken.net Hapjes Maken

    Great plugin, this is great for newbies like me ;)

  • Anand

    Hi Caphun,

    Cool plugin. I'm a newbie. I placed 10 Click to edit options in my page. When I try to save on one text field, remaining 10 text fields saves the some content. I would like to save different text in each. I used id=editable_01….Please help me.

  • Anand

    Hi, how can I use both save and hash (callback) options? I want to use multiple inline boxes and save them in database.

    • caphun

      @Anand – give each one a different ID then send the ID through to your backend script via ajax data. See the save.html example under demos.

  • notronwest

    This is a great plugin. Could you point to me how I would modify this slightly so that the event is triggered by a button that is not on the region that will be editable?

    E.g. I click a button and a sibling dom object becomes editable

  • notronwest

    Is there a way to turn this off?? I want to enable inline editing for a page. And then disable it. I changed the code to use ".on" instead of ".live" but I can't figure out a way to get this to turn off. Any help?

  • Pingback: 10 jQuery Live Page Edit Plugins | jQuery4u

  • Yesceeohhh

    I dont understand this part..
    $(function() {
    $('.editable').inlineEdit({
    buttonText: 'Add',
    save: function(e, data) {
    return confirm('Change name to '+ data.value +'?');
    }
    });
    });

    psd to joomla conversion

  • rodsanford

    Works in Safari browser on a PC, but I notice that it doesn't pick up the click event on the iPhone version of Safari…any ideas?