How do I replace div with textarea when I click button (including content)?
How do I replace div with textarea when I click button (including content)?
How do I replace div with textarea when I click button (including content)?
HTML: Add a button like below after every div.
If no background color is set on the Element, or its background color is set to 'transparent', the default end value will be white.
jQuery: Modify the code as below.
function divClicked() {
var divHtml = $(this).prev('div').html(); //select's the contents of div immediately previous to the button
var editableText = $("<textarea />");
editableText.val(divHtml);
$(this).prev('div').replaceWith(editableText); //replaces the required div with textarea
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}
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 () {
$(".btn").click(divClicked); //calls the function on button click
});
If you will run above code, you will get below output.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.