How do I make some text content in a div editable on click?
I want the editbox to be editable when we click on the div, when we do by clicking on "Div editable". It works great for one id. Can you please explain how to do this for multiple ids. Thanks in advance.
<table>
<tr>
<td>
Editable Div (double click text to the right, to enter edit mode) :
</td>
<td>
<div id="makeEditable">Div editable</div>
</td>
</tr>
</table>
(function($) {
$.fn.editable = function() {
var textBlock = $(this);
// Create a new input to allow editing text on double click
var textBox = $('<input/>');
textBox.hide().insertAfter(textBlock).val(textBlock.html());
// Hiding the div and showing a input to allow editing the value.
textBlock.dblclick(function() {
toggleVisiblity(true);
});
// Hiding the input and showing the original div
textBox.blur(function() {
toggleVisiblity(false);
});
toggleVisiblity = function(editMode) {
if (editMode == true) {
textBlock.hide();
textBox.show().focus();
// workaround, to move the cursor at the end in input box.
textBox[0].value = textBox[0].value;
}
else {
textBlock.show();
textBox.hide();
textBlock.html(textBox.val());
}
};
};
})(jQuery);
$(function() {
var $edit = $('#makeEditable').editable();
});
+3
source to share
3 answers
You have to rework your logic a bit. You have to create a separate entry for each div element and in the events that you have to use over the current dblclicked or blured element via this
. Here is a JSFiddle demo with minor modifications.
Hope this helps you. But I recommend using the attribute contenteditable
as @ apaul34208 unless you have any other custom js logic.
0
source to share