How to make a div editable on Click?


I would like to make div editable to enter contents in it and on changing content, want to call ajax to save data in back-end.

I know we can do it using Textbox, but would like to make a <div> inside <td> to make it editable when user clicks inside it.


Asked by:- bhanu
0
: 5351 At:- 11/27/2019 6:15:20 PM
jQuery make div editable on click







2 Answers
profileImage Answered by:- vikas_jk

To make <div> or <td> editable in your HTML, you can simply use "contenteditable" attribute for that element and it will be editable.

So according  to your requirement you can make it editable on load or on click

<div contenteditable="true">This is editable content.</div>

On Page Load:

Suppose, you want to make div with class .Editable on page loading simply use the jQuery code as below:

$(".Editable").attr("contenteditable","true");

All element's which has class "Editable" can have editable text inside div.

On Click Solution:

HTML

<div id="MainDiv">
  This is editable Content
</div>

jQuery

$("#MainDiv").on("click", function(){
  $(this).attr("contenteditable","true");
})

Working Fiddle link.

2
At:- 11/30/2019 8:03:27 AM


profileImage Answered by:- neena

The above answer is good, but if you want to convert HTML div into textarea on click, and make it editable, then you can achieve that also using below jQuery code

//make div editable using textarea
function divClicked() {
    var divHtml = $(this).html();
    var editableText = $("<textarea />");
    editableText.val(divHtml);
    $(this).replaceWith(editableText);
    editableText.focus();
    // setup the blur event for this new textarea
    editableText.blur(editableTextBlurred);
}

//on above editable textare leave, 
function editableTextBlurred() {
    var html = $(this).val();
    var viewableText = $("<div>");
    viewableText.html(html);
    $(this).replaceWith(viewableText);
    // setup the click event for this new div
    viewableText.click(divClicked);
}

$(document).ready(function() {
    $("div").click(divClicked); //call above function to create dynamic textare replacing div
});

In the above code, we are dynamically replacing div with textarea when user click's on it and then again replacing textarea contents with a div contents, when user leaves the 'textarea'

1
At:- 6/24/2021 11:00:30 AM
Thanks for this answer, but I think using "contenteditable" attribute is better. 0
By : bhanu - at :- 7/10/2021 12:32:40 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use