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.
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.
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'
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly