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.