Gracefully degrading jQuery edit-in-place
I recently became curious about creating some edit-in-place controls: things that look like static text until you click them, and they magically become editable. It turns out that creating this sort of thing is almost trivial with jQuery, which is now my favourite JavaScript framework. I’m a big fan of functional-style programming, and jQuery plays right into that.
It was still surprising that the bulk of what I wanted to do can be done in about 16 lines of code. That’s right: sixteen.
The plan was to create an edit-in-place system that would degrade nicely in browsers with JavaScript disabled. This isn’t necessarily as elegant as it could be and it doesn’t yet handle all input types, but that’s what version one is for! So without further ado, I present the code:
$.fn.in_place_edit = function() {
this.each(function() {
var $eip = $('<span></span>');
var $el=$(this).hide().after($eip);
$eip.text($el.val());
$eip.click(function(){ $eip.hide(); $el.data('origval', $el.val()).show().focus().select(); });
$el.blur(function(){
if($el.is('select')) $el.data('origval', $el.val());
$eip.text($el.data('origval')).show(); $el.hide().val($el.data('origval'));
});
$el.keydown(function(e){
if (e.which==27) $el.val($el.data('origval')).blur();
if (e.which==13||e.which==9) {
e.preventDefault();
$el.data('origval', $el.val()).blur();
}
});
});
};
Usage:
$(function(){ $('input, select').in_place_edit(); });
So, what does all this do? First of all, we create a new function on the main jQuery object, called in_place_edit
. This then iterates over elements matching the selector. It hides the input and creates a placeholder <span>
element with the input’s value. Then we simply set up event handlers to deal with the placeholder being clicked, the input losing focus, and various keypresses (enter/tab to accept, esc to cancel). To see it in action, I’ve put together a rough-and-ready demo.
Planned future enhancements:
- Checkbox input types (display using the labels?)
- Radio input types
- File input types (if possible)
- Textareas
- Any other types…
Maybe further updates later on!
Leave a Reply