Tiny Inline Edit Plugin For jQuery

December 31st | By | Back to Blog

Inline edit capability can be a very nice addition to any UI, here is a lightweight, inline-edit function I wrote with jQuery while working on a project.

The code:

$.fn.inlineEdit = function (replaceWith, connectWith) {

	$(this).hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	$(this).click(function() {
		
		var elem = $(this);
		
		elem.hide();		
		elem.after(replaceWith);
		replaceWith.focus();
				
		replaceWith.blur(function() {
			
			if ($(this).val() != "") {
				connectWith.val($(this).val()).change();
				elem.text($(this).val());
			}
								
			$(this).remove();			
			elem.show();
		});
	});
};

How to use

The HTML:

<form>
<input type="hidden" name="hiddenField" />
</form>

<p>Please edit me...</p>

The CSS:

p.hover { background: #fffbe1; }

The JS:

var replaceWith = $('<input name="temp" type="text" />'),
     connectWith = $('input[name="hiddenField"]');

$('p').inlineEdit(replaceWith, connectWith);

The code explained

In order to get started, you need to create an input element, which can be any type of form element, that will be used to replace the text node you’re looking to edit, replaceWith above. The second variable will be a hidden input field which will be used to store the value, connectWith above.

The basic idea here is that the inline-edit plugin does not remove the text node, it hides it and adds an input field which is connected to an hidden input. This might not be the best plugin if you need to cover all the bases, but it provides a solid logic foundation to create a lightweight, yet highly customizable inline-edit plugin.

Demo

The jQuery inline edit plugin can be used as-is, or it can be enhanced, see it in action in jsFiddle.


  • Gdhami

    Thank for the code man, I made few simple to add the ability to $.POST changes & handle Enter / ESC keys, if anyone is interested, here’s the fork:

    http://jsfiddle.net/Bz2PG/1/

  • Alex

    Neat & tidy. Great work.

  • Ivan

    Great code! Thanks!

    Took you code + Enter/Esc from Gdhami and added a function to limit the number of characters and some other formatting. Here is the fiddle: http://jsfiddle.net/igonzalez/KQGK3/1/