I have a span
element that I want to become editable upon double-click. (That is, the user can edit the text and it will save when s/he clicks outside.)
If you want a solution that works in ALL modern browsers, here's a nifty little jQuery plugin I made that emulates the functionality you described:
SIMPLY DROP THIS BLOCK INTO YOUR CODE-BASE:
//plugin to make any element text editable
//http://stackoverflow.com/a/13866517/2343
$.fn.extend({
editable: function() {
var that = this,
$edittextbox = $('').css('min-width', that.width()),
submitChanges = function() {
that.html($edittextbox.val());
that.show();
that.trigger('editsubmit', [that.html()]);
$(document).unbind('click', submitChanges);
$edittextbox.detach();
},
tempVal;
$edittextbox.click(function(event) {
event.stopPropagation();
});
that.dblclick(function(e) {
tempVal = that.html();
$edittextbox.val(tempVal).insertBefore(that).bind('keypress', function(e) {
if ($(this).val() !== '') {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
submitChanges();
}
}
});
that.hide();
$(document).click(submitChanges);
});
return that;
}
});
Now you can make any element editable simply by calling .editable() on a jQuery selector object, like so:
$('#YOURELEMENT').editable();
To get the changes after the user submits them, bind to the "editsubmit" event, like so:
$('#YOURELEMENT').editable().bind('editsubmit', function(event, val) {});
//The val param is the content that's being submitted.
Here's a fiddle demo: http://jsfiddle.net/adamb/Hbww2/