jQuery I have received many feature requests lately. Most of them have been worth of adding. People have different needs. But I have been worrying about jEditable becoming feature creep. Thats why I figured out another aproach.

For those in hurry. Check the custom input types demo for some proof on concept inputs.

Write your own input types

Sometimes you need multiple selects. Your form might need special third button which is not submit or cancel. Sometimes you want to use some other plugin such as Date Picker for editing.

There is no point adding separate parameter for all of these. Code would become bloated. Thus I have been working on enabling other developers to add new input types. Think of it as plugins for in place editor plugin.

Simple example

Let’s add new input type masked. It will be normal text input with Josh Bush’s Masked Input plugin applied.

$.editable.addInputType('masked', {
    element : function(settings, original) {
        var input = $('<input type="text">').mask(settings.mask);
        $(this).append(input);
        return(input);
    }
});

Code defines a method element(settings, original). It creates a new input and attaches Masked Input plugin. Input is then appended to form jEditable created. Form is available inside methods as this. Last the created input is returned.

Another example

Second example uses three out of five methods available to plugins. It will build timepicker from three selects. It uses Jason Huck’s Time Picker plugin.

$.editable.addInputType('timepicker', {
    element : function(settings, original) {
        var input = jQuery('<input type="hidden">');                
        $(this).append(input);
        return(input);
    },
    submit : function (settings, original) {
        var value = $("#h_").val() + ":" + $("#m_").val() + $("#p_").val();
        $("input", this).val(value);
    },
    plugin : function(settings, original) {        
        $("input", this).filter(":hidden").timepicker();
    }
});

First method element(settings, original) creates hidden input element. It will be used for storing the final value before submitting. Input is attached to form and returned. You always need to return the created element.

Second method submit(settings, original) is called before form is submitted. It collects hour, minute and am/pm from selects and creates a string. This string is the stored in previously created hidden input.

Third method plugin(settings, original) attaches Time Picker plugin to previously created hidden input. Again inside function the form is available as this.

Now when I have explained this I will tell you a tip. In this example you could leave out the element() method. If you don’t provide element() jEditable will create a hidden input by default.

For more examples you can check source code of example inputs in svn.

All methods explained

When creating custom input type you want to define one or several of these methods. None of them are mandatory.

$.editable.addInputType('example', {
    element : function(settings, original) { },
    content : function(string, settings, original) { },
    buttons : function(settings, original) { },
    submit  : function(settings, original) { },
    plugin  : function(settings, original) { }
});

All methods receive two parameters. Settings is jEditable settings hash. Original is the original element which was clicked. Method content() also receives third parameter string which is the value(s) input should be set to. Inside all methods this represents the form.

  • element(settings, original) should create input element and attach it to form. Form is available inside function as this. This input element stores the final value to be submitted to server. Finally function should return the newly created element. If you do not provide this method an hidden input will be created by default.
  • content(string, settings, original) should set the value of custom input. For example for multiple selects it should set the selected options in each select.
  • buttons(settings, original) should create and attach buttons to form. If this is not provided submit and cancel buttons are added according to settings hash.
  • submit(settings, original) is called before submitting the form. It should set the value of input element created by element(). This is only needed in special cases such as having multiple selects.
  • plugin(settings, original) can be used for attaching any 3rd party plugins.

This is second version of plugin api. First one was crap so I rewrote it. Currently I am hapy with it but I still would like to receive any feedback. If you write any custom input types let me know!

Download

Current release is 1.4.0RC1 1.4.0RC2 1.4.0RC3 1.4.0RC4 1.4.0. You can download several flavours: source, minified and packed. Do now forget to download example inputs!


16 Responses to “Custom input types for edit in place”

  1. Christopher says:

    Great plugin!

    Just so you know, the packed version linked above is throwing the following error on page load in FF2. The unpacked version is working fine. If your comment system strips out the error stuff below this, feel free to email me and I will send you the exact message I am getting.

    Error: missing ; before statement Source File: jquery.jeditable-1.4.0RC1.pack.js Line: 1, Column: 82 Source Code: });function reset(){self.innerHTML=self.revert;self.editing=false}});return(this)}jQuery.editable={types:{defaults:{element:function(settings,original){var input=jQuery(‘<input>‘);jQuery(this).append(input);return(input)},content:function(st

  2. Mika Tuupola says:

    Good catch. Thanks!

    Issue should have been fixed now. New packed version is here.

  3. Michael says:

    Thank you Mike

    Quick question? I am new to jquery and can somewhat read and follow what every line does but I would like to call .empty() before the editable text input is presented to clear what is a long underscore that is used as a placeholder on the page. E.g. Name ___

  4. Mika Tuupola says:

    Try something like this (untested code):

     $(document).ready(function() {
         $(".editable").editable("http://www.example.com/save.php", {
             type : "textarea",
             submit : "OK",
             data: function(value, settings) {
                 var retval = value.replace(/_/g, '');
                 return retval;
             }
         });
     });
    
  5. Will says:

    This plugin is fantastic.

    I think these new methods will do what I’m looking for but I can’t figure it out. Essentially, I need to add a class after submit if the content has changed.

    I’ve tried grabbing the current content and comparing to the content at submit but I’m obviously missing something. Can you point me in a direction?

    Thanks for all your work and thanks for sharing it.

    Will

  6. Mika Tuupola says:

    I actually found a bug in my code when writing you this example. So before trying this grab 1.4.0RC4.

    Then you can doe something like

     $.editable.addInputType('text_changed_checker', {
         element : function(settings, original) { 
             var input = $('<input>');
             $(this).append(input);
             return(input);        
         },
         submit  : function(settings, original) { 
             if (original.revert == $("input", this).val()) {
                 console.log('Unhanged.');           
             } else {
                 console.log('Changed.');
             }
         }
     });
    

    Rest is let as exercise to reader :)

  7. Tjarko Rikkerink says:

    Hi Mika, first of all thanks for this awesome script!! I just changed on little thing and maybe you can put that in your code. I use ColdFusion as backend and the return value has a lot of whitespace in it.. so I changed the self.innerHTML to the following to strip that whitespace

    self.innerHTML = jQuery.trim(str);

    Now I get the result back that I wanted and because it’s a default jQuery function it could be handy to build in the codebase. Just a suggestion :-)

  8. Mika Tuupola says:

    Basically backend should take care of not ouputting extra whitespace :) But since that is a small and convenient change it could be added. With possibility of shutting automatic trimming off of course.

  9. Eduardo says:

    Hi Mika!

    Thanks for such a nice plugin. I just started using it, and it’s great! I’m having troubles getting it to work with IE only when i’m using an URL to feed the data. Here’s what i have:

    $("#submission-status").editable("http://eclipsecon-gms.foxteck.homelinux.net/submissions/cooledit/9/submission-status", {
        loadurl   : 'http://eclipsecon-gms.foxteck.homelinux.net/submissions/json/9',
        type      : "select",
        tooltip   : 'Click to edit...',
        indicator : '<img src="/img/app/indicator.gif" alt="" />',
        submit    : "OK" 
    });

    The URL returns:

    {"ACCEPTED":"ACCEPTED","SCHEDULED":"SCHEDULED"}
    

    It doesn’t get any error message. Just an empty <select />.

    It works fine if I use data instead of loadurl:

    $("#submission-track").editable("http://eclipsecon-gms.foxteck.homelinux.net/submissions/cooledit/9/submission-track", {
            data      : '{"1":"Recommended","2":"Web Development"}',
            type      : "select",
            tooltip   : 'Click to edit...',
            indicator : '<img src="/img/app/indicator.gif" alt="" />',
            submit    : "OK" 
        });
    

    Note that both work just fine on Firefox and Opera. Any ideas?

    Thanks in advanced.

    PS. Sorry if i’m posting in the wrong place. Thanks again!

  10. Daniel Lin says:

    if i want to start editmode when i click a button outside the edit element,how to do this?

  11. Mika Tuupola says:

    Eduardo. I work primarily on OSX but will fire up Parallels to do some debugging with windows.

    Daniel. You could try something like this.

    $(document).ready(function() {
        $(".editable").editable("http://www.example.com/save.php", { 
            event  : 'dblclick',
            type   : 'textarea',
            submit : 'OK'
        });
        $(".editable_link").bind('click', function() {
            $(this).prev().dblclick();
        });
    });

    and the html itself would be:

     <p class="editable">Lorem Ipsum</p>
     <a class="editable_link">Click me to edit</a>
    
  12. Marc says:

    Hi, This is such a nice plugin and everything was going well until I has a problem that when a user removed the text they could no longer add it back as the element disappeared. I tried using the data: parameter as suggested above but got an value.replace does not exist error. Even the following code returns 0 to the item and not the value as expected. Am I totally doing this wrong ? Thanks

    $(”.editable”).editable(”<?php print $url ?>save.php”, {
      type : “textarea”,
      submit : “OK”,
      data: function(value, settings) {
        var retval = value;
        return retval;
      }
    });
    
  13. tanshul says:

    huh…one last question…now in all the examples the initial code has the classes say “ediatble2” in <h1>...<h1 class"editable2"...how can we use the same thing for input boxes to make them editable..i tried <:input type="text" class="editable2"...but this doesn't work at all...

    please do inform me…

    thanks in advance… tanshul.

  14. Mika Tuupola says:

    Jeditable is not ment to use with form elements. That kind of contradicts with meaning of in place editing. Use normal form instead. Or maybe you are looking for form plugin?

  15. Andrea Bersi says:

    A suggestion: with Internet Explorer the line 377 need to be a comment for no get a error if the input is select. Ciao

  16. Mika Tuupola says:

    Andrea: I am currently rewriting parts of Jeditable. Bug you mentioned should be fixed now. You might want to check latest version from svn.

Sorry, comments are closed for this article.