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 by 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.


How to learn from this program

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.