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 understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.