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


You can simplify things a bit by using contenteditable="true"

Working example

Main functions

<div id="makeEditable" contenteditable="true">Div editable</div>

      



Add some css as needed to make it more user friendly.

#makeEditable:focus{
    box-shadow: 0 0 2px blue;
}

      

MDN Documentation for Content Editing

+3


source


Just use basic jQuery selectors like: $ ('# MakeEditable, # anotherid, # anidagain')

But if you want to do this on multiple divs / elements, it is better to give all elements a class and apply this function to all elements of that class. Then your selector would be: $ ('Editable')

0


source







All Articles