Home / Programs / How do I replace div with textarea when I click button (including content)?
🚀 Programming Example

How do I replace div with textarea when I click button (including content)?

👁 204 Views
💻 Practical Program
📘 Step Learning

How do I replace div with textarea when I click button (including content)?

📌 Information & Algorithm

HTML: Add a button like below after every div.

Given Input:

 
<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.</div>
<button class='btn'>Edit</button>
 

jQuery: Modify the code as below.

Expected Output:

💻 Program Code

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
});
                        

📘 Explanation

If you will run above code, you will get below output.


📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.