I fiddled a litte more with Amyth's answer. This one just lets you click the text to edit it. You just need to add a class to any text element to enable the functionality. Enter key updates the text. Click outside the input to abort.
HTML:
<span class="edit-on-click">Click to edit</span>
JS:
$(document).ready(function() {
$('.edit-on-click').click(function() {
var $text = $(this),
$input = $('<input type="text" />')
$text.hide()
.after($input);
$input.val($text.html()).show().focus()
.keypress(function(e) {
var key = e.which
if (key == 13) // enter key
{
$input.hide();
$text.html($input.val())
.show();
return false;
}
})
.focusout(function() {
$input.hide();
$text.show();
})
});
});
JSFiddle
Update (implementing AJAX to update db value):
Here's how I ended up using it in practice:
this uses data attributes on the original element for id, model, and field to update in an ajax request. (This is from a Django app using Bootstrap, so some lines might be obsolete for you depending on your setup.)
HTML:
<span onclick="editOnClick(this)"
data-id="123"
data-model="myapp.MyModel"
data-field="my_field">Click to edit</span>
JS:
function editOnClick(el) {
var $text = $(el),
$input = $('<input type="text" />');
$text.hide()
.after($input);
$input.val($.trim($text.html())).show()
.tooltip({title:"press ENTER to save<br>click outside to cancel", container:"body", trigger:'focus', html:true})
.focus()
.keypress(function(e) {
var key = e.which;
if (key == 13) // enter key
{
$.ajax({
type: "POST",
data: {
value:$input.val(),
obj_id:$text.attr('data-id'),
obj_model:$text.attr('data-model'),
obj_field:$text.attr('data-field'),
csrfmiddlewaretoken:'{{ csrf_token }}'
},
url: "{% url 'edit_on_click' %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$input.hide();
$text.html(html)
.show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error: ' + XMLHttpRequest.responseText)
}
});
return false;
}
})
.focusout(function() {
$input.hide();
$text.show();
})
}