I tried more with Amit's answer. It just allows you to click the text to edit it. You just need to add the class to any text element to enable functionality. Enter the key, refresh the text. Press outside to cancel.
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)
Jsfiddle
Update (AJAX implementation to update db value):
Here's how I used it in practice: it uses the data attributes for the source element for the identifier, model, and update field in the ajax request. (This is from a Django application using Bootstrap, so some lines may be deprecated for you depending on your installation.)
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(); }) }
source share